反转局部链表

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

}

相关推荐
小饼干超人28 分钟前
详解向量数据库中的PQ算法(Product Quantization)
人工智能·算法·机器学习
你撅嘴真丑1 小时前
第四章 函数与递归
算法·uva
漫随流水1 小时前
leetcode回溯算法(77.组合)
数据结构·算法·leetcode·回溯算法
玄冥剑尊1 小时前
动态规划入门
算法·动态规划·代理模式
mjhcsp1 小时前
P14987 全等(mjhcsp)
算法·题解·洛谷
(❁´◡`❁)Jimmy(❁´◡`❁)1 小时前
Atcoder abc441A~F 题解
算法·深度优先·图论
少林码僧2 小时前
2.30 传统行业预测神器:为什么GBDT系列算法在企业中最受欢迎
开发语言·人工智能·算法·机器学习·ai·数据分析
豆沙沙包?2 小时前
2026年--Lc343-1926. 迷宫中离入口最近的出口(图 - 广度优先搜索)--java版
java·算法·宽度优先
超级大福宝2 小时前
【力扣200. 岛屿数量】的一种错误解法(BFS)
数据结构·c++·算法·leetcode·广度优先
独自破碎E2 小时前
【动态规划=递归+记忆化存储】跳台阶
算法·动态规划