Skip to content

Latest commit

 

History

History
24 lines (21 loc) · 1.08 KB

25.md

File metadata and controls

24 lines (21 loc) · 1.08 KB

LeetCode 25 Reverse Nodes in k-Group——hard

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
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
Note:
Only constant extra memory is allowed.
You may not alter the values in the list's nodes, only nodes itself may be changed.

思路:
头节点改变、设定dummy节点
1、得到链表的长度len
2、得到完整链表可以逆转的group数、num = len/k
3、两层循环、外层是循环是num数、是需要逆转的group数、
内层循环是k、是每次逆转的group里面的节点数
4、在这之间将每次循环之前的初始值、循环之后需要完成的连接做好
5、连接上尾巴上(<k)不能逆转的group、然后返回