[問題] linklist add時出現怪問題(已解決)
開發平台(Platform):GCC (Ex: VC++, GCC, Linux, ...)
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):現在問題變成 add函數裡面 top->ptr=NULL 這行註解掉跑display函數
就會出現無窮迴圈.. 不太懂為什麼以邏輯角度 這一行有沒有都無所謂不是嗎@@?
懇請大大幫忙解答
餵入的資料(Input):
預期的正確結果(Expected Output):
錯誤結果(Wrong Output):segmentation fault
程式碼(Code):
#include<stdlib.h>
#include<stdio.h>
typedef struct node{
int data;
struct node *ptr;
}node;
node *add(node*, int);
node *delete(node*);
void display(node*);
int isempty(node*);
node *first;
int main(void){
node *top;
top = NULL;
int s;
while(s != 4){
printf("輸入操作選項:(1)insert node;(2)delete node;(3)display(4)no
operation\n");
scanf("%d",&s);
switch(s)
{ case 1:
printf("輸入item\n");
int num;
scanf("%d", &num);
top = add(top, num);
break;
case 2:
top = delete(top);
break;
case 3:
display(first);
break;
default:
break;
}
}
return 0;
}
node *add(node *top, int item){
node *temp;
temp = (node*)malloc(sizeof(node));
if(top==NULL){
temp->ptr==NULL;
temp->data=item;
first=temp;
top=temp;
return top;
}
temp->ptr = top->ptr;
temp->data = item;
top->ptr = temp;
top=temp;
//top->ptr=NULL;
return top;
}
node *delete(node *top)
{
if(isempty(top))
printf("linklis is empty!\n");
else
{ int item;
node *temp = first;
while (temp->ptr != top)
{
temp = temp->ptr;
}
temp->ptr = top->ptr;
item = top->data;
free(top);
printf("delete node's item :%d\n",item);
return temp;
}
return NULL;
}
void display(node *first){
node *temp;
temp = first;
int i = 1;
while(temp != NULL)
{
printf("linklist 第%d個item:%d\n",i, temp->data);
i++;
temp = temp->ptr;
}
}
int isempty(node *top){
if(top==NULL)
return 1;
else
return 0;
}
補充說明(Supplement):
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.115.51.232
※ 編輯: okokokla2001 來自: 140.115.51.232 (10/03 22:40)
→
10/03 22:57, , 1F
10/03 22:57, 1F
→
10/03 23:04, , 2F
10/03 23:04, 2F
→
10/03 23:09, , 3F
10/03 23:09, 3F
→
10/03 23:19, , 4F
10/03 23:19, 4F
→
10/03 23:19, , 5F
10/03 23:19, 5F
※ 編輯: okokokla2001 來自: 140.115.51.232 (10/03 23:23)
→
10/03 23:26, , 6F
10/03 23:26, 6F
→
10/04 00:28, , 7F
10/04 00:28, 7F
→
10/04 00:29, , 8F
10/04 00:29, 8F
→
10/04 00:33, , 9F
10/04 00:33, 9F
→
10/04 00:34, , 10F
10/04 00:34, 10F
→
10/04 11:46, , 11F
10/04 11:46, 11F
※ 編輯: okokokla2001 來自: 140.115.51.232 (10/04 14:58)
※ 編輯: okokokla2001 來自: 140.115.51.232 (10/04 15:11)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章