反转链表 & 初始化 & 只转m和n之间

1、描述

反转一个单向链表
题目链接

2、关键字

反转

3、思路

3步迭代
递归

4、notes

3步迭代
1、保存后方 tem=cur->next
2、反指前方 cur->next=pre
3、迭代前进 pre=cur; cur=tem;

5、复杂度

时间:O(N)
空间:O(1)

6、code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

// 初始化
Node* ini(vector<int>& nums, int n) {
    Node* dummy = new Node(0);
    Node* head = dummy;
    for(int i = 0; i < n; i++) {
        Node* newNode = new Node(nums[i]);
        newNode->next = head->next;
        head->next = newNode;
    }
    delete dummy;
    return head->next;
}


class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head || !head->next) return head;  // 特判0,1
        ListNode * pre=nullptr;  // 初始化
        auto cur=head;
        auto tem=head;
        //while(!cur){  *******************************             又是这里             !!!!!!!
        while(cur){
            tem=cur->next;  //保存后方
            cur->next=pre;  // 反指前方

            pre=cur;  // 迭代前进
            cur=tem;
        }
        return pre;
    }
};

三、翻转其中的一部分

给你单链表的头节点 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
题解

/**
 * 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) {
        if(left==right) return head;
        ListNode* dummy_head=new ListNode(0,head);  // 构造函数,使->next=head
        ListNode* t1=dummy_head;
        
        int ind=0;
        while(ind < left-1){
            t1 = t1->next;
            ind++;
        }
        ListNode* l_left=t1;  // 翻转左边的最后元素,
        t1 = t1->next;
        ind++;
       
        ListNode* cur = t1;  // 翻转的第一个元素
        ListNode* pre = nullptr;  // 从翻转第一个元素开始,设置pre节点
        ListNode* t2=cur;  //  记录第一个节点,等最后好用     
        
        while(left <= right){
            ListNode* next = cur->next;  // 1、暂存后一个节点
            cur-> next  = pre;  // 2、后指向前一个
            pre = cur;   //  3、前进
            cur = next;  //  3、同步前进
            left ++;           
        }
        l_left->next = pre;
        t2->next = cur;
        
        return dummy_head->next;
    }
};


题目描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值