反转局部链表

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

}

相关推荐
8Qi81 小时前
LeetCode 516:最长回文子序列
算法·leetcode·职场和发展·动态规划
youngerwang2 小时前
【从搬运工到协处理器:网卡芯片架构、算法、验证与边缘演进深度剖析】
网络·算法·架构·芯片
想要成为糕糕手2 小时前
前端必修课:JavaScript 数组与数据结构底层逻辑全解析
javascript·数据结构·面试
KaMeidebaby2 小时前
卡梅德生物技术快报|纯化重组蛋白实操详解
人工智能·python·tcp/ip·算法·机器学习
手写码匠3 小时前
从零实现 Prompt 工程引擎:结构化提示、自动优化与多轮自省体系
人工智能·深度学习·算法·aigc
无限码力4 小时前
阿里算法岗 0530笔试真题 - 多约束条件下的元素匹配统计
算法·阿里笔试真题·阿里机试真题·阿里算法岗笔试
lqqjuly4 小时前
MLA — 多头潜在注意力深度解析
深度学习·神经网络·算法
吴可可1234 小时前
SolidWorks草图转三维DWG技巧
算法
tyung4 小时前
Go 手写 Wait-Free SPSC 无界队列:无 CAS、无锁、泛型节点池
数据结构·后端·go
redaijufeng5 小时前
C++雾中风景7:闭包
c++·算法·风景