2014-02-10 27 views
0

實現使用鏈表隊列我實現使用鏈表隊列中C.這是我的結構 -錯誤使用C

typedef struct llist node; 
struct llist 
{ 
    int data; 
    node *next; 
}; 

在執行push()我現在面臨的問題。這裏是我的push()定義 -

void push(node *head,int n) 
{ 
    if (head==NULL) 
    { 
     head=(node *)(malloc((sizeof(node)))); 
     head->data=n; 
     head->next=NULL; 
     printf("=>%d\n",head->data); 
    } 
    else 
    { 
     node *ptr; 
     ptr=head; 
     while(ptr->next!=NULL) 
     { 
      ptr=ptr->next; 
     } 
     ptr->next=(node *)(malloc((sizeof(node)))); 
     ptr=ptr->next; 
     ptr->data=n; 
     ptr->next=NULL; 
    } 
    return; 
} 

,這裏是我的main()功能 -

int main() 
{ 
    int choice,n; 
    node *head; 
    head=NULL; 
    while(1) 
    { 
     printf("Enter your choice -\n1. Push\n2. Pop\n3. Exit\n"); 
     scanf("%d",&choice); 
     switch(choice) 
     { 
      case 1: 
       printf("Enter element to push: "); 
       scanf("%d",&n); 
       push(head,n); 
       if (head==NULL)//To check if head is NULL after returning from push() 
       { 
        printf("Caught here!\n"); 
       } 
       break; 
      case 2: 
       pop(head); 
       break; 
      case 3: 
       return 0; 
     } 
    } 
} 

現在的問題是,經過在case 1push()退出,head再次成爲NULL,即抓到這裏來!語句確實得到執行。這怎麼可能?

+3

您正在'push()'中修改列表的本地副本。要修改'main()'中的一個,你需要一個雙指針。 'push()'應該是'void push(node ** head,int n)',並且在'push()'中使用'head'的任何位置,您應該使用'* head',而您應該通過'push &head,n)'當你打電話時。 – leif

+0

'main'函數中的'head'和''pop'函數中的'head'是兩個不同的變量。 – ajay

回答

5

由於您按值調用並且正在修改該值(在本例中爲節點*頭),因此該值不會保留在main()中。因此,無論

  1. 通行證指向節點*頭

    push(&head,n);main()

    和修改

    void push(node **head,int n)

  2. 返回頭

    node* push(node *head,int n)

    main()

    head=push(head,n);

0

只是增加了接受的答案,另一種選擇是宣告頭變量爲全局。那麼你不需要將頭部作爲參數推送或彈出。

+0

是的,我確實保留它作爲備份選項。但我想知道爲什麼上面的代碼不工作。任何方式很好的建議。 – nsane