反转链表
反转链表
问题:给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
这里有三种方法对链表进行反转:
- 递归
- 栈
- 双链表(实际上只是对原链表进行变化)
递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
// 递归
if(head==NULL||head->next==NULL) return head;
ListNode* p=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return p;
}
};
栈
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//栈
if(head==NULL||head->next==NULL) return head;
stack<ListNode*> mystack;
while(head!=NULL)
{
mystack.push(head);
head=head->next;
}
ListNode* res=mystack.top();
mystack.pop();
ListNode* ans=res;
while(!mystack.empty())
{
res->next=mystack.top();
res=res->next;
mystack.pop();
}
res->next=NULL;
return ans;
}
};
双链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//双链表
ListNode* newlist=NULL;
while(head!=NULL)
{
ListNode* temp=head->next;
head->next=newlist;
newlist=head;
head=temp;
}
return newlist;
}
};