首页 > 代码库 > 【leetcode刷题笔记】Reverse Nodes in k-Group

【leetcode刷题笔记】Reverse Nodes in k-Group

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, only nodes itself may be 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


 

题解:思路很简单,一步步做就可以了。除了题目要求实现的函数,另外实现了两个函数:

 private ListNode[] reverseSub(ListNode head,int k) 该函数将head所指向的长度为k的链表反转,返回一个大小为2的数组,数组中第一个元素是反转后的链表的头节点,第二个元素是反转后的链表的尾节点。

 private int getlength(ListNode head) 该函数返回head所指向的链表的长度。

在reverseKGroup函数中,首先计算原链表的长度len,那么需要反转的组的数目就是len/k,接下来调用reverseSub函数len/k次,反转每一段链表,然后根据返回的首尾指针把它们串起来。最后根据len%k是否为0判断链表中是否有不需要反转的元素,如果有,把它们链在链表最后面返回。

代码如下:

 1 /** 2  * Definition for singly-linked list. 3  * public class ListNode { 4  *     int val; 5  *     ListNode next; 6  *     ListNode(int x) { 7  *         val = x; 8  *         next = null; 9  *     }10  * }11  */12 public class Solution {13     private ListNode[] reverseSub(ListNode head,int k){14         ListNode[] answer = new ListNode[2];15         answer[1] = head;16         ListNode prev = null;17         for(int i = 0;i < k;i++){18             ListNode temp = head.next;19             head.next = prev;20             prev = head;21             head = temp;22         }23         answer[0] = prev;24         return answer;25     }26     private int getlength(ListNode head){27         int count = 0;28         while(head != null){29             count ++;30             head = head.next;31         }32         return count;33     }34 35     public ListNode reverseKGroup(ListNode head, int k) {36         int len = getlength(head);37         if(len < k)38             return head;39         40         ListNode answer = null;41         ListNode tail = new ListNode(0);42         int for_num = len / k;43         for(int i = 0;i < for_num;i++){44             ListNode h = head;45             46             //find next starter47             for(int j = 0;j < k;j++)48                 head = head.next;49             50             ListNode[] temp = reverseSub(h, k);51             if(answer == null){52                 answer = temp[0];53                 tail = temp[1];54             }55             else {56                 tail.next = temp[0];57                 tail = temp[1];58             }                        59         }60         61         if(len%k != 0)62             tail.next = head;63         else64             tail.next = null;65         66         return answer;67     }68 }