Reverse a singly linked list.
recursively
/**
* 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* p = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return p;
}
};
iteratively
用了vector存下来。
/**
* 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* p = head;
ListNode* q = new ListNode(0);
q->next = p;
vector<int> v;
while(head){
v.push_back(head->val);
head = head->next;
}
for(int i = v.size()-1; i>=0;--i){
p->val = v[i];
p = p->next;
}
return q->next;
}
};
iteratively 直接改
/**
* 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* pre = NULL;
while(head){
ListNode* next = head->next; //先保存下来 不然下一条语句会改变
head->next = pre;
pre = head;
head = next;
}
return pre;
}
};