[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

 

分析:

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

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

 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     public ListNode reverseKGroup(ListNode head, int k) {
14         int len = 0;
15         ListNode headbp = head;
16         while(headbp != null){
17             len++;
18             headbp = headbp.next;
19         }
20         if(len < 2){return head;}
21         
22         int reverseTimes = (len / k);
23         
24         ListNode myhead = new ListNode(0);
25         myhead.next = head;
26         ListNode curr = myhead;
27         ListNode next = head;
28         ListNode prev = null;
29         ListNode rhead = curr;
30         ListNode rtail = curr.next;
31         
32         for(int j=0;j<reverseTimes;j++){
33             rhead = curr; 
34             rtail = curr.next; 
35             curr = curr.next;             
36             next = curr;
37             for (int i = 0; i < k; i++) {
38                 next = next.next;
39                 curr.next = prev;
40                 prev = curr;
41                 curr = next;
42             }
43             rhead.next = prev;
44             rtail.next = next;
45             prev = null;
46             curr = rtail;
47         }
48         return myhead.next;
49     }
50 }

 

转载于:https://www.cnblogs.com/xuning/p/4430792.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值