反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL 輸出: 5->4->3->2->1->NULL
進階:
你可以迭代或遞歸地反轉鏈表。你能否用兩種方法解決這道題?
方法1:
設置三個指針進行反轉,one和two負責反轉,three負責暫存下一個位置。
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;
ListNode *one=head, *two=one->next, *three=two->next;
head->next = NULL;
while (two) {
two->next = one;
one = two;
two = three;
if (three) three = three->next;
}
return one;
}
方法2:遞歸
關鍵點在於要記錄尾結點,並且head->next要置空,否則在修改時會出問題
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;
ListNode* tail = reverseList(head->next);//記錄尾結點
head->next->next = head;
head->next = NULL;
return tail;
}