反转局部链表

#include <iostream>

#include <set>

using namespace std;

struct Node {

int val;

Node* next;

Node(int v, Node* n): val(v), next(n) {}

};

Node* rev(Node* head, int l, int r) {

Node pre(0, head);

Node* first = &pre;

while (l > 1 && first != nullptr) {

first = first->next;

l--;

}

if (first == nullptr) {

return head;

}

cout << "first->val:" << first->val << endl;

auto second = first->next;

int diff = r - l;

while (diff > 0 && second->next != nullptr) {

auto tmp = second->next;

second->next = tmp->next;

tmp = second;

first->next = tmp;

cout << "first :" << first->val << endl;

diff--;

}

return pre.next;

}

int main() {

Node* n5 = new Node(5, nullptr);

Node* n4 = new Node(4, n5);

Node* n3 = new Node(3, n4);

Node* n2 = new Node(2, n3);

Node* n1 = new Node(1, n2);

int left = 2;

int right = 5;

auto res = rev(n1, left, right);

while (res != nullptr) {

cout << res->val << " ";

res = res->next;

}

cout << endl;

return 0;

}

相关推荐
快去睡觉~1 小时前
力扣73:矩阵置零
算法·leetcode·矩阵
小欣加油1 小时前
leetcode 3 无重复字符的最长子串
c++·算法·leetcode
月盈缺4 小时前
学习嵌入式的第二十二天——数据结构——双向链表
数据结构·学习·链表
猿究院--王升4 小时前
jvm三色标记
java·jvm·算法
一车小面包5 小时前
逻辑回归 从0到1
算法·机器学习·逻辑回归
科大饭桶6 小时前
C++入门自学Day14-- Stack和Queue的自实现(适配器)
c语言·开发语言·数据结构·c++·容器
tt5555555555556 小时前
字符串与算法题详解:最长回文子串、IP 地址转换、字符串排序、蛇形矩阵与字符串加密
c++·算法·矩阵
元亓亓亓7 小时前
LeetCode热题100--101. 对称二叉树--简单
算法·leetcode·职场和发展
躲在云朵里`7 小时前
深入理解数据结构:从数组、链表到B树家族
数据结构·b树
不会学习?7 小时前
算法03 归并分治
算法