问题描述: 输入若干(不超过100个)非负整数,创建一个不带头结点的单向链表。 再输入一个位置index以及一个数据data,程序中首先创建一个新结点s,s的数据成员为data,然后调用函数insertNode将s插入到链表的指定位置index处,最后输出结果链表。
输入说明: 首先输入若干非负整数,每个整数作为数据放入一个链表结点中,输入-1表示输入结束。然后输入若干组整数,每组一行,每行包含两个整数,第一个表示需要插入位置index,第二个为新结点的数据。如:输入“1 5”表示在链表的第一个位置(最前面)插入一个结点,结点的数据为5。
输出说明: 对于每组输入,输出插入结点之后的结果链表。输出的信息以head开头,以tail结尾,以“–>”分隔。具体见输出范例。如果输入的index超出了链表的范围(如果链表中已有n个结点,则index的有效范围为 1<= index <= n+1),则不插入,输出原链表。如果是空链表,则直接输出“head–>tail”。
输入范例: 1 2 3 -1 1 10 3 20
输出范例: head–>10–>1–>2–>3–>tail head–>10–>1–>20–>2–>3–>tail
#include<iostream> using namespace std; struct ListNode{ int num; struct ListNode *next; }; ListNode *createByTail(){ ListNode *head; ListNode *p1,*p2; int n=0,num; cin>>num; head=NULL; if(num==-1){ return NULL; } while(num!=-1){ p1=new ListNode; p1->num=num; n=n+1; if(n==1) head=p1; else p2->next=p1; p2=p1; cin>>num; } p2->next=NULL; return head; } ListNode *insert(ListNode *head,int locate,int data){ ListNode *p=head,*pre=head,*p1; int n=0; while(p){ n++; p=p->next; } if(locate<=0||locate>n+1){ return head; } p=head; if(locate==1){ p1=new ListNode; p1->num=data; p1->next=head; head=p1; return head; } int count=1; while(count!=locate-1){ count++; p=p->next; } p1=new ListNode(); p1->num=data; p1->next=p->next; p->next=p1; return head; } void displayLink(ListNode *head){ ListNode *p; p=head; cout<<"head-->"; while(p!= NULL){ cout<<p->num<<"-->"; p=p->next; } cout<<"tail\n"; } int main(){ ListNode *head=createByTail(); int index,data; while(cin>>index>>data){ head=insert(head,index,data); displayLink(head); } }