[問題] 新手reverse linked list debug
https://onlinegdb.com/ryscef5gU
程式新手入門debug,弄了兩個小時還弄不對QQ
如上程式碼連結
功能在於反轉串列
這邊僅貼上有問題的function code
void reverse_list(node *s)
{
node *x=new node();
node *p=new node();
node *q=new node();
p=x=s; //p, x都初始化為list頭s
q=NULL; //q初始化為list的bottom=Null
while(p->link!=NULL)
{
x->link=q; //x指回前一個node q
q=p; //q變成p
p=p->link; //p再往後搜索一格
x=p; //x也是p
}
s=x; //把s這個頭設為x即收工
}
但是最後因為這個function code拿到segmentation fault結果
謝謝賜教!!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.226.156.95 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1578930659.A.836.html
→
01/14 00:06,
5年前
, 1F
01/14 00:06, 1F
推
01/14 00:56,
5年前
, 2F
01/14 00:56, 2F
→
01/14 00:58,
5年前
, 3F
01/14 00:58, 3F
→
01/14 11:00,
5年前
, 4F
01/14 11:00, 4F
→
01/14 13:34,
5年前
, 5F
01/14 13:34, 5F
→
01/14 13:36,
5年前
, 6F
01/14 13:36, 6F
感謝各位耐心解說!
我又把reverse function重新寫過,在副程式內試著偷print出來結果是沒問題的。
但是現在發現問題點是在我回傳到main會回傳失敗,僅剩最後一個node指向null
看起來我回傳的功能寫得有問題...
int main()
{
node *t=new node();
t->link=NULL;
t->data=1;
for(int i=2;i<4;i++)
{
node *y=new node();
y->data=i;
y->link=t;
t=y;
}
print_list(t);
reverse_list(t); //reverse完成應該把list head回傳到t
printf("Reverse the list t:\n");
print_list(t); //但是會發現只印了最後一個node指向null
return 0;
}
void reverse_list(node *s)
{
node *prev=new node();
node *curr=new node();
node *temp=new node();
curr=s;//curr初始化為list頭
prev=NULL; //prev初始化成new list的bottom=null
while(curr!=NULL)
{
temp=curr->link; //temp儲存下一個node位址
curr->link=prev; //目前的node指回上一個node prev
prev=curr; //prev前進到目前的node
curr=temp; //目前node前進到temp存的位址
}
s=prev;
printf("Reverse the list prev偷印看看:\n");
print_list(s); \\在副程式結束前先偷印印看list head確認結果無誤
}
OUTPUT:
Original list t:
address=0xabbc60 data=3 nextpoint=0xabbc40
address=0xabbc40 data=2 nextpoint=0xabbc20
address=0xabbc20 data=1 nextpoint=(nil)
Reverse the list prev偷印看看:
address=0xabbc20 data=1 nextpoint=0xabbc40
address=0xabbc40 data=2 nextpoint=0xabbc60
address=0xabbc60 data=3 nextpoint=(nil)
Reverse the list t: //回傳失敗了
address=0xabbc60 data=3 nextpoint=(nil)
※ 編輯: Moderator (36.226.156.95 臺灣), 01/14/2020 18:02:16
推
01/14 18:26,
5年前
, 7F
01/14 18:26, 7F
→
01/14 18:27,
5年前
, 8F
01/14 18:27, 8F
→
01/14 19:40,
5年前
, 9F
01/14 19:40, 9F
推
01/14 19:46,
5年前
, 10F
01/14 19:46, 10F
→
01/14 23:21,
5年前
, 11F
01/14 23:21, 11F
推
01/22 11:56,
5年前
, 12F
01/22 11:56, 12F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章