給出一個鏈表,每?k?個節點一組進行翻轉,并返回翻轉后的鏈表。
k?是一個正整數,它的值小于或等于鏈表的長度。如果節點總數不是?k?的整數倍,那么將最后剩余節點保持原有順序。
示例 :
給定這個鏈表:1->2->3->4->5
當?k?= 2 時,應當返回:?2->1->4->3->5
當?k?= 3 時,應當返回:?3->2->1->4->5
public class ReverseNodesInkGroup {public static void main(String[] args) {// 1 -> 2 -> 3 -> 4 -> 5ListNode node1 = new ListNode(1);ListNode node2 = new ListNode(2);ListNode node3 = new ListNode(3);ListNode node4 = new ListNode(4);ListNode node5 = new ListNode(5);node1.next = node2;node2.next = node3;node3.next = node4;node4.next = node5;ListNode reverseKGroup = reverseKGroup(node1, 3);System.out.println("=================");while (reverseKGroup != null) {System.out.println(reverseKGroup.val);reverseKGroup = reverseKGroup.next;}}public static ListNode reverseKGroup(ListNode head, int k) {ListNode currentNode = head;int count = 0;while (currentNode != null && count != k) { // 每k個節點一組分隔currentNode = currentNode.next;count++;}if (count == k) {currentNode = reverseKGroup(currentNode, k);/// 遞歸的解決子問題while (count-- > 0) { // 將頭節點從鏈表中切掉,放在下一組鏈表的前端,切除k次,即可將鏈表翻轉ListNode temp = head.next; // 保存該組鏈表的第二個節點head.next = currentNode; // head節點的下一位指向currentNode(第一次循環時是下一組鏈表的頭節點,之后每截取一次就往前移)currentNode = head; // currentNode節點前移到headhead = temp; // head節點重新指向該組的第一個節點,開始下次循環}head = currentNode; //最終,該段的所有節點將會截空,head應指向currentNode}return head;}}
?