LeetCode 92反转链表||-中等
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 92反转链表||-中等
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你單鏈表的頭指針 head 和兩個整數 left 和 right ,其中 left <= right 。請你反轉從位置 left 到位置 right 的鏈表節點,返回 反轉后的鏈表 。
輸入:head = [1,2,3,4,5], left = 2, right = 4
輸出:[1,4,3,2,5]
示例 2:
輸入:head = [5], left = 1, right = 1
輸出:[5]
提示:
鏈表中節點數目為 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;} };總結
以上是生活随笔為你收集整理的LeetCode 92反转链表||-中等的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 143 重排链表-中等
- 下一篇: 图的最小生成树和最短路径算法思路总结(P