Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
反转链表,该题是比较经典的一道题了,无论是剑指offer还是leetcode上,都对该题有提及和较高的评价,该题是对链表这种数据结构的一种考察。
递归解法:
/**
* 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* p = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return p;
}
};
非递归解法:
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr)
return head;
ListNode *p = head, *new_p = nullptr;
while(p != nullptr)
{
ListNode* tmp_p = p->next;
p->next = new_p;
new_p = p;
p = tmp_p;
}
return new_p;
}