Topic
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 left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, and only nodes itself is 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
Resolution
Test instructions: The original linked list K K of the reversal, if the last remaining less than K nodes, then remain unchanged.
No special algorithm, I think the focus is how to use the extra space to reverse the K nodes, with three pointers curtail, Curhead, Posthead,curtail point to reverse the tail node, Curhead point to the inverted head node, Posthead is the reversal process The latter node of the Curhead, which is used for auxiliary inversion. This method can be compared with the topic "Leetcode" Reverse Linked List II Problem Solving report
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * Next = Null *} *} */public class Solution {public ListNode Reversekgroup (ListNode head, int k) {if (head = = NULL | | K < 2) return head; ListNode prehead = new ListNode (0); Prehead.next = head; int cnt = 0; ListNode node = head; Iterative node ListNode lasttail = prehead;//Last node after the reversal of K nodes listnode curtail = head; The end node of the K-node to be reversed listnode curhead = head; This time the head node of the K node to be reversed listnode posthead = null; This time a node behind the head node of the K node to be reversed while (node! = null) {cnt++; node = Node.next; Invert this k node if (cnt = = k) {ListNode tmp = Curtail.next; while (tmp! = node) {posthead = Curhead; Curhead = tmp; TMP = Tmp.next; Curhead.next = Posthead; } Lasttail.next = curhead;//The K node of the reversal to the last k node after lasttail = curtail; Curtail = node; curhead = node; CNT = 0; }}//If there are less than k nodes in the back, direct it to the previous linked list lasttail.next = Curhead; return prehead.next; }}
Related topics: "Leetcode" Reverse Linked List II Problem Solving report
"Leetcode" Reverse Nodes in K-group problem solving report