目錄
- 題目描述:
- 示例 1:
- 示例 2:
- 代碼實現:
題目描述:
給你單鏈表的頭指針 head 和兩個整數 left 和 right ,其中 left <= right 。請你反轉從位置 left 到位置 right 的鏈表節點,返回 反轉后的鏈表 。
示例 1:
輸入:head = [1,2,3,4,5], left = 2, right = 4
輸出:[1,4,3,2,5]
示例 2:
輸入:head = [5], left = 1, right = 1
輸出:[5]
代碼實現:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode reverseBetween(ListNode head, int left, int right) {ListNode tmp = new ListNode(-1);// 設置啞結點tmp.next = head;// 啞結點指向頭節點// pre指向啞結點ListNode pre = tmp;// 使pre指向反轉鏈表的前一個結點for (int i = 0; i < left - 1; i++) {pre = pre.next;}ListNode rightNode = pre;// 記錄反轉鏈表的前一個結點for (int i = 0; i < right - left + 1; i++) {rightNode = rightNode.next;// 找到反轉鏈表的尾結點}ListNode leftNode = pre.next;// 記錄反轉鏈表的頭節點ListNode endList = rightNode.next;// 記錄反轉鏈表的后一個結點// 斷開原來鏈表:將需要反轉的鏈表切割開pre.next = null;// 切割頭節點rightNode.next = null;// 切割尾結點// 反轉鏈表操作reverseLinkedList(leftNode);// 連接鏈表操作pre.next = rightNode;// 原先反轉鏈表的前驅 指向 現在反轉之后的鏈表的右節點(也就是現在的頭節點)leftNode.next = endList;// 反轉之后的鏈表左節點(也就是現在的尾結點) 指向 原先反轉鏈表的后繼// 返回啞結點的后繼return tmp.next;// 這里不返回head結點的原因是:在反轉操作時,head已經指向反轉鏈表的尾結點了}// 反轉函數反轉了結點之間的指向,head指向的是反轉之后的尾結點void reverseLinkedList(ListNode head) {ListNode cur = head;// 頭節點開始遍歷ListNode pre = null;// 前驅結點while (cur != null) {ListNode next = cur.next;// 記錄后繼結點cur.next = pre;// 結點指向前驅pre = cur;// 前驅指針指向當前結點cur = next;// 當前指針指向后繼結點}}
}