反转局部链表

#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;

}

相关推荐
淡海水5 小时前
07-04-并发-ConcurrentBag-T-工作窃取WorkStealing算法
开发语言·算法·c#·bag·concurrent·workstealing
leobertlan6 小时前
好玩系列:训练一个神经网络模型指导小孩玩游戏2-大局观教练
算法
Tisfy7 小时前
LeetCode 3876.构造奇偶一致的数组 II:三种情况分类讨论(其实还是脑筋急转弯)
算法·leetcode·题解·脑筋急转弯
乐迪信息7 小时前
智慧港口船舶AI算法实现在线状态监测
大数据·人工智能·深度学习·算法·计算机视觉
kiracrimson8 小时前
从缓存的角度看链表与线性表的差异
数据结构·链表·缓存
木井巳9 小时前
【BFS/DFS 解决 FloodFill 算法】太平洋大西洋水流问题
java·算法·leetcode·深度优先·广度优先·宽度优先·推荐算法
心抵鹊9 小时前
归并排序之翻转对(hard)
数据结构·算法
白山编程大哥9 小时前
Java 集合算法:从排序、查找到底层原理的实战指南
java·python·算法
shehuiyuelaiyuehao10 小时前
算法34,位运算符操作,总结
算法
Navigator_Z10 小时前
LeetCode //C - 1224. Maximum Equal Frequency
c语言·算法·leetcode