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;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步