反转局部链表

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

}

相关推荐
SamsongSSS1 分钟前
JavaScript逆向SM国密算法
javascript·算法·逆向
图灵信徒4 分钟前
2025 ICPC Gran Premio de Mexico 3ra Fecha
c++·算法·codeforcrs
大锦终5 分钟前
【算法】栈专题
数据结构·c++·算法·leetcode
haogexiaole5 分钟前
资源图分配算法
算法
天选之女wow8 分钟前
【代码随想录算法训练营——Day6(Day5周日休息)】哈希表——242.有效的字母异位词、349.两个数组的交集、202.快乐数、1.两数之和
数据结构·算法·leetcode·散列表
寒冬没有雪10 分钟前
利用归并算法对链表进行排序
c++·算法
CoovallyAIHub10 分钟前
AI帮你打标签!这个开源神器让数据标注快了90%
深度学习·算法·计算机视觉
古译汉书11 分钟前
蓝桥杯算法之基础知识(7)---排序题的快排和归并排序
算法
JJJJ_iii12 分钟前
【左程云算法07】队列和栈-链表数组实现
数据结构
薛定谔的算法16 分钟前
JavaScript队列实现详解:从基础到性能优化
javascript·数据结构·算法