單鏈表反轉

2022-10-05 05:57:10 字數 1137 閱讀 8267

/* 

題目: 給你單鏈表的頭節點 head ,請你反轉鍊錶,並返回反轉後的鍊錶

*/#include #include typedef struct listnode listnode;

//初始化乙個單鏈表

listnode * link_list_create_from_tail(int *data,int length)

//初始化鍊錶為空

head->next = null;

//必須申明乙個指向新插入結點的指標,用來標識插入新結點位置

//開始時候p指向head結點

listnode *p = head;

for(int i=0;ival = data[i];

//由於每次插入都是最後乙個,所以結點的next指標始終指向null

node->next = null;

//前乙個結點指標就是p的next指向新結點

p->next = node;

//然後把指標指向新結點

p = node;

}return head->next;

}// 反轉單鏈表

struct listnode* reverselist(struct listnode* head)

return prev;

}//遍歷單向鍊錶

//head: 傳入頭結點

void print_linkedlist(listnode * head)

//由於頭結點不儲存資料,故從下乙個結點遍歷資料

//申明指標p,指向頭結點的下一結點

listnode *p = head;

//迴圈鍊錶,直到指標p為空

while(p)

}int main(int argc,char *ar**)

; listnode *tail1 = link_list_create_from_tail(data1,2);

print_linkedlist(tail1);

printf("\n");

listnode *head = reverselist(tail1);

print_linkedlist(head);

return 0;

}

單鏈表反轉

單鏈表反轉,可以用迴圈做,當然也可以遞迴 詳見 include includestruct node 3 1 4 6 2 1 1 3 4 6 2 2 4 1 3 6 2 3 6 4 1 3 2 4 2 6 4 1 3 5 迴圈反轉,即依次改動3個指標值,直到鍊錶反轉完成 比如,上面第 1 行到第 2...

反轉單鏈表

include stdafx.h include include using namespace std struct listnode typedef listnode plistnode typedef plistnode list list creatlist return head void...

單鏈表反轉

想起很早以前某次面試,面試官很嚴肅的要求我現場手寫單鏈表反轉的 哥虎軀一震,心想 不就需要要個臨時變數來記錄位址嗎,用得著這樣煞有介事?雖然在那之前我的確沒寫過這個程式,哈哈哈 當時我草草寫了十來行 面試官不等我完成,就直接拿過去開始問問題。不知道是不是因為抗壓能力不足,在面試官的不斷 盤問 下,哥...