標籤:
題意:把一個鏈表倒過來。
題解:有遞迴和非遞迴兩種方式,主要就是考察指標操作的熟悉程度。
遞迴的方法:
/** * 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||!(head->next))return head; ListNode* p=reverseList(head->next); head->next->next=head; head->next=nullptr; return p; }};
非遞迴:就一個一個轉過來方向就好了。轉的時候需要用兩個輔助指標,一個指向該節點的前一個節點,一個指向後一個節點。
/** * 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||!(head->next))return head; ListNode* pre=nullptr; ListNode* back=head->next; while(back){ head->next=pre; pre=head; head=back; back=back->next; } head->next=pre; return head; }};
leetcode 206. Reverse Linked List