Day-1 反转链表

AcWing 35.反转链表

思路:

1.指针反向

2.维护相邻两个指针(a,b)

a,b同时向后跳一位

c = b - > next;

b - > next = a;

a = b, b = c;

3.直到a走到结尾

4.头结点next 指空

迭代版本

/**
 * 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 || !head -> next ) //链表为空或只有一个点
            return head;
        auto a = head, b = a -> next;
        
        while(b)
        {
            auto c = b ->next;
            b -> next = a;
            a = b, b = c;
        }
        head -> next = NULL;
        return a;
    }
};

递归版本

1.用递归的方法,将第二个节点之后的链表反转,反转后第二个节点的指针指空;

2.让第二个节点的指针指向第一个节点

head -> next -> next = head;

3.最后让头结点指空

head -> next = NULL;

/**
 * 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 || !head -> next) return head;
        
        auto tail = reverseList(head -> next);
        head -> next -> next = head;
        head -> next = NULL;
        return tail;
    }
};

LeetCode 92.反转链表II

思路:头结点有可能会变,也可能不变,这时我们需要创建一个虚拟头结点。(虚拟头结点随意定义一个数值就可以)

/**
 * 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* reverseBetween(ListNode* head, int left, int right) {
        auto dummy =  new ListNode(-1);
        dummy -> next = head;
        auto a = dummy;
        for(int i = 0; i < left - 1; i ++ ) a = a -> next;
        auto b = a -> next, c = b -> next;
        for(int i = 0; i < right - left; i ++ )
        {
            auto d = c -> next;
            c -> next = b;
            b = c, c = d; 
        }
        a -> next -> next = c;
        a -> next = b;
        return dummy -> next;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值