LeetCode 92反转链表||-中等
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 92反转链表||-中等
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給你單鏈表的頭指針 head 和兩個(gè)整數(shù) left 和 right ,其中 left <= right 。請(qǐng)你反轉(zhuǎn)從位置 left 到位置 right 的鏈表節(jié)點(diǎn),返回 反轉(zhuǎn)后的鏈表 。
輸入:head = [1,2,3,4,5], left = 2, right = 4
輸出:[1,4,3,2,5]
示例 2:
輸入:head = [5], left = 1, right = 1
輸出:[5]
提示:
鏈表中節(jié)點(diǎn)數(shù)目為 n 1 <= n <= 500 -500 <= Node.val <= 500 1 <= left <= right <= n代碼如下:
/*** 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) {ListNode *dummy = new ListNode;ListNode *pre = dummy;pre->next = head;for (int i = 0;i<left-1;i++){pre = pre->next;}ListNode *cur = pre->next;ListNode*next;for (int i =0;i<right-left;i++){next = cur->next;cur->next = next->next;next->next = pre->next;pre->next = next;}ListNode *index = dummy->next;delete dummy;return index;} };總結(jié)
以上是生活随笔為你收集整理的LeetCode 92反转链表||-中等的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: LeetCode 143 重排链表-中等
- 下一篇: 图的最小生成树和最短路径算法思路总结(P