反转局部链表

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

}

相关推荐
Liu628886 小时前
C++中的工厂模式高级应用
开发语言·c++·算法
AI科技星6 小时前
全尺度角速度统一:基于 v ≡ c 的纯推导与验证
c语言·开发语言·人工智能·opencv·算法·机器学习·数据挖掘
条tiao条7 小时前
KMP 算法详解:告别暴力匹配,让字符串匹配 “永不回头”
开发语言·算法
干啥啥不行,秃头第一名7 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
tobias.b7 小时前
计算机基础知识-数据结构
java·数据结构·考研
zzh940777 小时前
Gemini 3.1 Pro 硬核推理优化剖析:思维织锦、动态计算与国内实测
算法
2301_807367197 小时前
C++中的解释器模式变体
开发语言·c++·算法
愣头不青8 小时前
617.合并二叉树
java·算法
MIUMIUKK8 小时前
双指针三大例题
算法
灵感__idea8 小时前
Hello 算法:复杂问题的应对策略
前端·javascript·算法