leetcode 206 Reverse Linked List
方法一:头插法
方法二:递归法
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<string>
#include<string.h>
#include<queue>
#include<algorithm>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* reverseList2(ListNode* head) {
ListNode *phead=head, *pnext=head->next;
phead->next = NULL;
while(pnext)
{
ListNode *tmp = pnext->next;
pnext->next = phead;
phead = pnext;
pnext = tmp;
}
return phead;
}
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode * new_head = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return new_head;
}
int main()
{
ListNode n1(6), n2(2), n3(3), n4(4),n5(5);
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
ListNode *tmp = reverseList(&n1);
while (tmp)
{
cout << tmp->val << " ";
tmp = tmp->next;
}
cout << endl;
return 0;
}