1. 程式人生 > >Reverse Nodes in k-Group LeetCode Java

Reverse Nodes in k-Group LeetCode Java

eno number out etc lte sta lin time rop

描述
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then le-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example, Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5

分析

給定鏈表,一次反轉鏈表k的節點並返回其修改的列表。
如果節點的數目不是k的倍數,那麽最終的節點應該保持原樣。
可能不會更改節點中的值,而只能更改節點本身。

例如,給定這個鏈表:1>2>3>4>5。
對於k=2,你應該返回:2 ->1 ->4>3>5。
對於k=3,你應該返回:3 ->2 ->1>4>5。

註意越界問題,

代碼

 1 public static ListNode reverseNodeInKGrop(ListNode head, int n) {
 2         if (head == null || head.next == null || n == 1)
 3             return
head; 4 ListNode fakehead = new ListNode(-1); 5 fakehead.next = head; 6 ListNode ptr1 = head, ptr2 = fakehead.next.next, newstart = fakehead; 7 int len = 0; 8 while (ptr1 != null) { 9 len++; 10 ptr1 = ptr1.next; 11 } 12 ptr1 = fakehead.next;
13 if(n!=len) 14 n = n % len; 15 int k = len / n; 16 for (int j = 0; j < k; j++) { 17 18 for (int i = 1; i < n; i++) { 19 ptr1.next = ptr2.next; 20 ptr2.next = newstart.next; 21 newstart.next = ptr2; 22 ptr2 = ptr1.next; 23 } 24 25 for (int i = 0; i < n; i++) { 26 newstart = newstart.next; 27 } 28 29 if (ptr2 != null && ptr2.next != null) { 30 ptr1 = newstart.next; 31 ptr2 = ptr1.next; 32 } 33 } 34 35 return fakehead.next; 36 }

Reverse Nodes in k-Group LeetCode Java