LeetCode---206. 反转链表

题目描述:反转一个单链表。
示例:
输入: 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;
   }
};  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值