2014-02-10 28 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