實現使用鏈表隊列我實現使用鏈表隊列中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 1
push()
退出,head
再次成爲NULL
,即抓到這裏來!語句確實得到執行。這怎麼可能?
您正在'push()'中修改列表的本地副本。要修改'main()'中的一個,你需要一個雙指針。 'push()'應該是'void push(node ** head,int n)',並且在'push()'中使用'head'的任何位置,您應該使用'* head',而您應該通過'push &head,n)'當你打電話時。 – leif
'main'函數中的'head'和''pop'函數中的'head'是兩個不同的變量。 – ajay