在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
1 public static LinkedListNode ReverseNodesinkGroupOpt(LinkedListNode head, int k) 2 { 3 if (k <= 1) 4 return head; 5 6 LinkedListNode fakehead = new LinkedListNode(); 7 fakehead.Next = head; 8 LinkedListNode prev_tail = fakehead; 9 LinkedListNode curr = head; 10 LinkedListNode next = head; 11 LinkedListNode tail = head; 12 13 while (curr != null) 14 { 15 for (int i = 1; i < k; i++) 16 { 17 curr = curr.Next; 18 if (curr == null) 19 return fakehead.Next; 20 next = curr.Next; 21 } 22 23 curr.Next = null; 24 ReverseSignlyLinkedListIterative(tail); 25 26 prev_tail.Next = curr; 27 prev_tail = tail; 28 tail.Next = next; 29 curr = next; 30 tail = next; 31 } 32 33 return fakehead.Next; 34 } 代码分析: 虽然这题操作到head不是corner case,但是我还是加了一个fakehead在前面,模拟前面一个sub linked list的tail, prev_tail。 非常方便,如果k 大于linkedlist长度,返回的是fakehead.Next, 就是head。 如果k 小于 linkedlist 长度,fakehead.Next 将会指向第一个sub list的 head。
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论