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* pre = new ListNode(-1);
pre->next = head;
ListNode* cur = head;
ListNode* nex = head;
while(cur->next){
nex = cur->next;
cur->next = nex->next;
nex->next = pre->next;
pre->next = nex;
}
return pre->next;
}
};
递归:递归地把后一个元素放到前一个元素前面。
class Solution {
public:
ListNode *reverseList(ListNode *head) {
return f(head, NULL);
}
ListNode *f(ListNode *cur, ListNode *pre){
if(not cur)
return pre;
ListNode *post = cur->next;
cur->next = pre;
return f(post, cur);
}
};