206. Reverse Linked List
解法一(递归方法)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode *p = head->next;
ListNode *cur = reverseList(p);
p->next = head;
head->next = NULL;
return cur;
}
};
解法二(迭代方法)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL || head->next == NULL)
return head;
ListNode *pre = head;
ListNode *p = head->next;
ListNode *temp;
pre->next = NULL;
while(p != NULL){
temp = p->next;
p->next = pre;
pre = p;
p = temp;
}
return pre;
}
};