Leetcode 92. Reverse Linked List II
思路:添加头节点,反转链表某个连续部分,206. Reverse Linked List是本题的特殊情况,也可以像本题一样做,具体见Leetcode 206. Reverse Linked List。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode reverseBetween(ListNode head, int m, int n) { 11 if(head == null) return head; 12 ListNode dummy = new ListNode(0); 13 dummy.next = head; 14 ListNode pre = dummy; 15 for(int i = 0; i < m - 1; i++) pre = pre.next;//移动m-1次 16 ListNode start = pre.next; 17 ListNode then = start.next; 18 for(int i = 0; i < n - m; i++) {//需要将start后面的n-m个点陆续反转 19 start.next = then.next;//start的后面指向then的后面 20 then.next = pre.next;//then的后面指向pre的后面,相当于将then插入pre和pre.next之间 21 pre.next = then;//pre的后面是then 22 then = start.next;//完成一个元素的反转后,then指向下一个准备被反转(插入pre和pre.next之间)的节点 23 } 24 return dummy.next; 25 } 26 }
Next challenges: