[leetcode]算法题目 - Reverse Nodes in k-Group

时间:2023-12-27 19:22:31

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

分析:

链表操作,本身用不上什么高大上的算法或者数据结构。不过其中那些繁杂的小细节很容易搞得头大,很少能有人把这种题目一次写对吧。更可恨的是,就算写完了,隔一天在看自己之前写的思路,依然要费好多脑细胞才能理清楚。。。。。

这道题的思路是,先计算出来链表的长度len,然后len除以k就得到我们总共需要反转几个子链表。反转链表的操作本身不难,难的在于两个子链表衔接的部分。你必须要记录清楚这个子链表的尾巴和头部,并在合适的时机设置它们指向的节点……总之很难用文字描述清楚,直接上代码吧。。就这么几行代码折腾了俩小时才搞定。

 /**
* 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) {
int len = 0;
ListNode headbp = head;
while(headbp != null){
len++;
headbp = headbp.next;
}
if(len < 2){return head;} int reverseTimes = (len / k); ListNode myhead = new ListNode(0);
myhead.next = head;
ListNode curr = myhead;
ListNode next = head;
ListNode prev = null;
ListNode rhead = curr;
ListNode rtail = curr.next; for(int j=0;j<reverseTimes;j++){
rhead = curr;
rtail = curr.next;
curr = curr.next;
next = curr;
for (int i = 0; i < k; i++) {
next = next.next;
curr.next = prev;
prev = curr;
curr = next;
}
rhead.next = prev;
rtail.next = next;
prev = null;
curr = rtail;
}
return myhead.next;
}
}