鏈表的反轉(遞歸和非遞歸兩種)
鏈表的反轉
示例
輸入:1->2->3->4->5
輸出:5->4->3->2->1
- 遞歸
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL|| head->next == NULL)
{
return head;
}
ListNode * newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
};
- 非遞歸
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseList2(ListNode* head) {
if (head == NULL || head->next == NULL)
{
return head;
}
ListNode * newHead = NULL;
while (head != NULL)
{
ListNode * tmp = head->next;
head->next = newHead;
newHead->next = head;
head = tmp;
}
return newHead;
}
};