反转局部链表

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

}

相关推荐
hello_lain36 分钟前
9.1 简单排序(冒泡、插入)(排序(上))
c语言·数据结构·算法·排序算法
炬火初现39 分钟前
Hot100——普通数组
算法·leetcode·职场和发展
啊我不会诶1 小时前
【数据结构】字典树
数据结构·算法
信奥卷王1 小时前
[GESP202403 五级] 成绩排序
数据结构·算法
小欣加油1 小时前
leetcode 494 目标和
c++·算法·leetcode·职场和发展·深度优先
Jiezcode3 小时前
LeetCode 55.跳跃游戏
c++·算法·leetcode·游戏
wheeldown3 小时前
【Leetcode高效算法】用双指针策略打破有效三角形的个数
python·算法·leetcode
蒙奇D索大4 小时前
【数据结构】数据结构秘籍:如何衡量“查找”的快慢?ASL是关键!
数据结构·笔记·学习·考研
蒙奇D索大4 小时前
【数据结构】考研重点掌握:顺序查找算法实现与ASL计算详解
数据结构·笔记·学习·考研·算法·改行学it
TTGGGFF4 小时前
MATLAB仿真:编程基础实验全解析——从入门到实战
数据结构·算法·matlab