Leetcode-25 Reverse Nodes in k-Group, leetcode-25k-group
Problem description:
Given a linked list, reverse the nodes of a previous listKAt a time and return its modifiedlist.
If the number of nodes is not a multipleKThen left-out nodes in the end shouldremain as it is.
You may not alter the values in the nodes, only nodesitself may be changed.
Only constant memory is allowed.
For example,
Given this linked list:1->2->3->4->5
ForK= 2, you shoshould return:2->1->4->3->5
ForK= 3, you shoshould return:3->2->1->4->5
Problem Analysis:
This problem can be converted into a subproblem of reverse linked list.
Http://blog.csdn.net/woliuyunyicai/article/details/45027883)
The original linked list should be divided into multiple groups based on the value of k according to the question settings, and the connections between the front and back linked lists should be paid attention. Therefore, you must record the group information before and after, record the last node of the preGroup of the previous group, and record the last node of nextGroup, the linked list after the current grouping is reversed is linked together with the front and back linked list.
Code:
Class ListNode {int val; ListNodenext; public ListNode (int val) {this. val = val ;}} public classSolution {public ListNodereverseKGroup (ListNode head, int k) {// if (k = 1 | head = null | head. next = null) return head; // secondary node to return the final result ListNoderesultNode = newListNode (0); resultNode. next = head; // write down the first node of each layer and the last node ListNodetailNode = head; ListNodeheadNode = head; // write down the last node of the previous group and the last Node ListNodepreGroup = resultNode; ListNodenextGroup = resultNode; // count int count = 1 for each layer of group; while (tailNode! = Null) {// arrive at the end of the group and reverse the group if (count = k) {// record the first node nextGroup = tailNode of the next group. next; // flip this group linked list reverseList (headNode, tailNode); // note that after the flip, tailNode is the first node of the current group, headNode is the last node // link to the previous group and the next group preGroup. next = tailNode; headNode. next = nextGroup; // prepare the next loop preGroup = headNode; headNode = nextGroup; tailNode = nextGroup; count = 1; continue;} count ++; // keep repeating down and find the last node tailNode = tailNode of the group. next;} return r EsultNode. next;} // reverse linked list private void reverseList (ListNodehead, ListNode tail) {ListNodepreNode = newListNode (0); preNode. next = head; ListNodesucNode = null; // This is different from general reverse linked list questions. Here, you do not need to consider the case of null while (preNode! = Tail) {sucNode = head. next; head. next = preNode; preNode = head; head = sucNode ;}}}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.