Given the head of a linked list, reverse the nodes of the list k at a time, and return the 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.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Example 2:
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Constraints:
The number of nodes in the list is n.
1 <= k <= n <= 5000
0 <= Node.val <= 1000
Follow-up: Can you solve the problem in O(1) extra memory space?
Solutions
Solution 1: Simulation
We can simulate the entire reversal process according to the problem description.
First, we define a helper function $\textit{reverse}$ to reverse a linked list. Then, we define a dummy head node $\textit{dummy}$ and set its $\textit{next}$ pointer to $\textit{head}$.
Next, we traverse the linked list, processing $k$ nodes at a time. If the remaining nodes are fewer than $k$, we do not perform the reversal. Otherwise, we extract $k$ nodes and call the $\textit{reverse}$ function to reverse these $k$ nodes. Then, we connect the reversed linked list back to the original linked list. We continue to process the next $k$ nodes until the entire linked list is traversed.
The time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$.
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcreverseKGroup(head*ListNode,kint)*ListNode{dummy:=&ListNode{Next:head}pre:=dummyforpre!=nil{cur:=prefori:=0;i<k;i++{cur=cur.Nextifcur==nil{returndummy.Next}}node:=pre.Nextnxt:=cur.Nextcur.Next=nilpre.Next=reverse(node)node.Next=nxtpre=node}returndummy.Next}funcreverse(head*ListNode)*ListNode{vardummy*ListNodecur:=headforcur!=nil{nxt:=cur.Nextcur.Next=dummydummy=curcur=nxt}returndummy}
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int val = 0, ListNode next = null) { * this.val = val; * this.next = next; * } * } */publicclassSolution{publicListNodeReverseKGroup(ListNodehead,intk){vardummy=newListNode(0);dummy.next=head;varpre=dummy;while(pre!=null){varcur=pre;for(inti=0;i<k;i++){if(cur.next==null){returndummy.next;}cur=cur.next;}varnode=pre.next;varnxt=cur.next;cur.next=null;pre.next=Reverse(node);node.next=nxt;pre=node;}returndummy.next;}privateListNodeReverse(ListNodehead){ListNodeprev=null;varcur=head;while(cur!=null){varnxt=cur.next;cur.next=prev;prev=cur;cur=nxt;}returnprev;}}