2012-01-28 102 views
0
void addToEnd() 
{ 
    newnode = (struct node*)malloc(sizeof(struct node)); 

    printf ("Enter the customer name :"); 
    scanf ("%s", newnode->cName); 

    printf ("\nEnter customer number :"); 
    scanf ("%d", &newnode->cNumber); 

    printf ("\nEnter transaction description :"); 
    scanf ("%s", newnode->tDescrip); 

    newnode->next = NULL; 
    if(list==NULL) 
     list = newnode; 
    else if (list != NULL && newnode < list) 
    { 
     newnode->next = list; 
     list = newnode; 
    } 
    else 
    { 
     temp = list; 
     while (temp != NULL) 
     { 
      if (newnode > temp) 
      { 
       prev = temp; 
       temp = temp->next; 
      } 
     } 
     newnode->next = prev->next; 
     prev->next = newnode; 
    } 
} 

我想這代碼,但那朵代碼只需添加到開始而不是結束,我怎麼想的節點添加到盡頭?怎麼節點添加到末尾(單鏈表)

+1

你需要找到結束。 – 2012-01-28 06:22:13

回答

2

讓我們看看,以下是否不容易理解。

簡單地改變指針:

struct node** tail = &list; 
while (*tail != NULL) { 
    tail = &((*tail)->next); 
} 
*tail = newnode; 
+0

爲什麼這個代碼很少被發現?它是C更好,比java更具表現力的地方之一。沒有'如果',簡潔的代碼。 – 2012-01-28 06:50:00

1

請仔細閱讀以下附加功能中鏈表添加節點

append(int num) 
{ 
    struct node *temp,*r; 
    /* CREATING A NODE AND ASSIGNING A VALUE TO IT */ 

    temp= (struct node *)malloc(sizeof(struct node)); 
    temp->data=num; 
    r=(struct node *)p; 

    if (p == NULL) /* IF LIST IS EMPTY CREATE FIRST NODE */ 
    { 
     p=temp; 
     p->next =NULL; 
    } 
    else 
    { /* GO TO LAST AND ADD*/ 

     while(r->next != NULL) 
      r=r->next; 
      r->next =temp; 
      r=temp; 
      r->next=NULL; 
    } 
}/* ADD A NEW NODE AT BEGINNING */