連結清單結構
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
leetcode 206 單連結清單反轉——(考察指針)
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階:
你可以疊代或遞歸地反轉連結清單。你能否用兩種方法解決這道題?
思路:
疊代
設定兩個指針(new_head和next),new_head始終使其指向新連結清單的頭結點,next始終使其指向待反轉連結清單的頭結點。
步驟圖示如下(渣繪)

代碼如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if((head==nullptr)||(head->next==nullptr))
return head;
ListNode * new_head=nullptr,*next=nullptr;
while(head){
//next指向待排序連結清單的頭結點
next=head->next;
//令被拆下來的節點的next指針指向新連結清單的頭結點
head->next=new_head;
//移動new_head,使其保持指向新連結清單的頭結點
new_head=head;
//使head指向待排序連結清單的頭結點
head=next;
}
return new_head;
}
};
遞歸
遞歸着将連結清單層層拆解,等遇到尾節點時,将其設定為連結清單的頭結點,之後層層從遞歸中傳回,将之前記錄的節點設定為目前連結清單的尾節點。類似下圖(渣繪,求原諒):
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* helper(ListNode* head){
ListNode* current_head=nullptr;
ListNode* head_next=nullptr;
if ((head == NULL)||(head->next == NULL)){
return head;
}else{
//記下目前的頭結點a0
current_head = head;
//記下目前頭結點後面的結點a1
head_next = head->next;
//傳回(a1...an)逆轉後的頭結點
head = helper(head_next);
//用上面儲存的位址(逆轉後的尾結點)指向原來的頭結點a0
head_next->next = current_head;
//将a0的next域置零
current_head->next = NULL;
}
//傳回a0
return head;
}
ListNode* reverseList(ListNode* head) {
if((head==nullptr)||(head->next==nullptr))
return head;
ListNode * tail=nullptr;
tail=helper(head);
return tail;
}
};