帶頭結點的單鏈表反轉
阿新 • • 發佈:2019-01-12
struct Node { int data; Node *next; };
方法一:就地逆序
主要思路:在遍歷連結串列的時候,修改當前結點的指標域的指向,讓其指向前驅結點。
為此,需要用三個指標變數分別指向當前結點、前驅結點、後繼結點。遍歷完所有的結點後,即可以完成指標的逆序。最後,讓頭節點的指標域指向原來最後一個元素結點。
void reverse(Node* head) {
if (head->next == NULL) return;
Node* pre = NULL; Node* cur = head->next; Node* next;
while (cur) { next = cur->next; cur->next = pre; pre = cur; cur = next; } head->next = pre; }
方法二:插入法
主要思路:從連結串列的第二個結點開始,把遍歷到的結點插入到頭結點的後面,直到遍歷結束。
void reverse(Node* head) { if (head->next == NULL) return; Node*cur, *next; cur = head->next->next;//cur初始指向第二個結點(不包括頭結點) head->next->next = NULL; while (cur) { next = cur->next; cur->next = head->next; head->next = cur; cur = next; } }