题目内容:
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
解题思路之前提到过,直接贴代码:
迭代解法:
/**
* 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 == NULL)
return NULL;
ListNode *newHead = head, *p = head->next;
head->next = NULL;
while(p != NULL) {
ListNode *temp = p;
p = p->next;
temp->next = newHead;
newHead = temp;
}
return newHead;
}
};
递归解法:
/**
* 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) {
ListNode *new_head;
reverseList(head, new_head);
return new_head;
}
ListNode* reverseList(ListNode *head, ListNode *&new_head) {
if(head == NULL || head->next == NULL) {
new_head = head;
return head;
}
ListNode *temp = head->next;
head->next = NULL;
reverseList(temp, new_head)->next = head;
return head;
}
};