Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Solution:
/**
* 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 *lead = new ListNode(-1);
lead->next = head;
ListNode *pre = head, *p = head->next;
while(p)
{
pre->next = p->next;
p->next = lead->next;
lead->next = p;
p = pre->next;
}
return lead->next;
}
};