我在之前一篇博客《C語言實現單鏈表(不帶頭結點)的逆序打印》中詳細實現了對一個不帶頭節點的鏈表的逆序打印,整體思路也是非常的簡單,也就是依次遍歷原鏈表,然後把取出的節點用頭插法建立一個新的鏈表,新鏈表就是原鏈表的逆序。這篇博客我會來實現使用帶頭結點的鏈表實現逆序,思路同上述是一樣的。
核心代碼如下:
/**
* 整體思路就是取出一個節點,然後使用頭插法建立一個新鏈表,新鏈表就是逆序後的。
*/
Node *ReverseList(Node *pNode){
Node *reverseList;
InitialList(&reverseList);//初始化逆序後的鏈表
Node *pMove;
Node *pInsert;
pInsert = (Node*)malloc(sizeof(Node));
memset(pInsert, 0, sizeof(Node));
pInsert->next = NULL;
pMove = pNode->next;
while (pMove != NULL) {
//頭插法
pInsert->element = pMove->element;
pInsert->next = reverseList->next;
reverseList->next = pInsert;
//插入節點重新分配內存
pInsert = (Node*)malloc(sizeof(Node));
memset(pInsert, 0, sizeof(Node));
pInsert->next = NULL;
pMove = pMove->next;
}
printf("%s函數執行,逆序帶頭節點的單鏈表創建成功\n",__FUNCTION__);
PrintList(reverseList);
return reverseList;
}