题目描述:反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
1.三指针法
/**
* 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==nullptr)
return nullptr;
ListNode* pre=nullptr,*cur=nullptr,*next=nullptr;
cur=head;
next=head->next;
while(next!=nullptr)
{
cur->next=pre;
pre=cur;
cur=next;
next=next->next;
}
cur->next=pre;
return cur;
}
};
2.头插法
/**
* 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==nullptr||head->next==nullptr)
return head;
//cur指向被插入的节点
ListNode* cur=head;
ListNode* next=nullptr;
//next是要头插的节点
while(head->next!=nullptr)
{
//先保存要插入的节点
next=head->next;
//让头节点往后指向next的下个节点
head->next=next->next;
//将要插入节点插入到cur前面
next->next=cur;
//更新cur,让cur指向下次被插入节点
cur=next;
}
return cur;
}
};
3.递归法
class Solution {
public:
//递归子函数
ListNode* resv(ListNode* cur,ListNode* next)
{
if(next!= nullptr)
{
ListNode* head = resv(next,next->next);
next->next= cur;
cur->next =nullptr;
return head;
}
else
{
return cur;
}
}
ListNode* reverseList(ListNode* head)
{
//3.递归方法
if(head==nullptr||head->next==nullptr)
return head;
ListNode *tmp = resv(head, head->next);
return tmp;
}
};