题目描述
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表
示例一
输入:head = [1,2,3,4,5], left = 2, right = 4 输出:[1,4,3,2,5]
示例二
输入:head = [5], left = 1, right = 1 输出:[5]
个人C++解答
GYL
一遍过+0ms击败100%可喜可贺,但是内存消耗有点巨大,不过能用O(N)解决的话内存消耗大一点是必然的啦,主要思路是用辅助栈来模拟反转链表,将left到right的数据入栈,构建result的时候在left到right之间的数据出栈。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseBetween(ListNode* head, int left, int right) { stack<int> stk; ListNode *result = new ListNode(); ListNode *p = head; int step = 1; while(step!=right+1){ if(step>=left && step<=right){ stk.push(p->val); } p = p->next; step++; } step = 1; ListNode *q = result; while(head!=nullptr){ if(step>=left && step<=right) { q->next = new ListNode(stk.top()); stk.pop(); }else{ q->next = head; } head = head->next; q = q->next; step++; } return result->next; } };