查看底部的最后一个函数i_at().
#include#include #include #define nl printf("\n") #define pf printf #define si(a) scanf("%d",&a) #define sc(a) scanf("%c",&a); struct node{ int val; struct node *next; }; struct node *first,*last,*damn,*temp,*prev,*newnode; void i_beg(); void i_end(); void display(); void del(); void i_at(); struct node *create(int); main() { int val,i,j; char key;val=1; while(val<6 && val>0){ pf("\n1.Start \t2.End \t3.Display\t4.Delete\t5.Insert\t6.Exit\n------------------------------------------------\n"); si(val); if(val==6)exit(0); else{ switch(val){ case 1: i_beg(); break; case 2: i_end(); break; case 3: display();break; case 4: del(); break; case 5: i_at();break; case 6: exit(0);break; } } } } struct node * create(int val){ newnode = (struct node *)malloc(sizeof( struct node)); if(newnode == NULL) { pf("Oops! You have gone out of memory\n"); return 0; } else { newnode -> val = val; newnode -> next = NULL; return newnode; } } void i_beg(){ int x; //if(first -> val == last -> val && first == NULL) pf("Only one node exists!!!\n "); pf("Enter a value to insert\t"); si(x); newnode = create(x); if(first == last && first == NULL) { first = last = newnode; first -> next = NULL; last -> next = NULL; pf("\n %d inserted at first\n",x); } else { temp = first; first = newnode; first -> next = temp; pf("\n %d inserted at first\n",x); } } void i_end(){ int x; //if(first -> val == last -> val && first == NULL) pf("Only one node exists!!!\n "); pf("Enter a value to insert\t"); si(x); newnode = create(x); if(first == last && first == NULL) { first = last = newnode; first -> next = NULL; last -> next = NULL; pf("\n %d inserted at last\n",x); } else { last -> next = newnode; last = newnode; last -> next = NULL; pf("\n %d inserted at last\n",x); } } void display(){ prev = first; while(prev != NULL) { pf("%d -> ",prev -> val); prev = prev -> next; }pf(" NULL"); nl; } void del(){ pf("Enter the position to delete\t"); int i,pos;si(pos); for(prev = first,i=1 ; i next,i++);// not i< pos but i next; prev -> next = temp->next; } void i_at(){ pf("Enter the position to add after this position\t"); int i,pos;si(pos); for(prev = first,i=1 ; i next,i++); pf("Enter a value to insert\t"); si(i); newnode = create(i); temp = prev; // order of these statements is important newnode -> next = temp -> next; prev -> next = newnode; pf("%d inserted after position %d\n",i,pos); }
如果我把这些行写成
prev -> next = newnode; newnode -> next = temp -> next;
那么display()函数出错了.但是,如果我将这两行的顺序颠倒过来
newnode -> next = temp -> next; prev -> next = newnode;
然后代码正在运行.这只是将新节点链接到链接列表的问题.那么,如果我交换代码中所示的那两行的顺序,为什么代码错了呢?
例如:要将b连接到a&c,如果连接(b-> c优先,a-> b秒)或(a-> b优先,b-> c秒,则无关紧要. 错误在哪里?
当你这样做时:
temp = prev;
你是不是复制结构,你只是在混淆的名称prev
的名称temp
,因为两者都是指针.
所以当你这样做时:
prev -> next = newnode; newnode -> next = temp -> next;
要更改的字段的值next
两者的prev
和temp
,而第二条语句是不正确.
在另一种情况下,更新顺序是正确的.