25. Reverse Nodes in k-Group(java)

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

译文:
给定一个链表,分别反转链表的k个结点并返回修改后的链表。

  1. 如果链表的结点数量不是k的倍数,那么你需要将余下的结点保留在末尾;
  2. 你不能改变结点中的值,你只能改动结点的位置。

对于这道题,我已尽我所能却没有一丝的想法,后面去参考了别人的博客,看了别人的想法才明白。心里面不禁暗自的“夸奖”自己,原来我在算法这块儿这么“强”。这道题主要可以用递归的思想去做,然后采用头插法逆序建表。不了解头插法建表的童鞋可以先去了解一下,之后再来做这道题目。下面附上改进后的代码:

public class Solution
{
     public ListNode reverseKGroup(ListNode head, int k)
     {
         if(head == null)
             return head;
         if(head.next == null)
             return head;

         ListNode cur = head;
         int count = 0;

         while(cur != null && count != k)
         {
             cur = cur.next;
             count++;
         }

         if(count == k)
         {
             cur = reverseKGroup(cur, k);
             /*
              * 使用头插法建立逆序链表
              */
             while(--count >= 0)
             {
                 ListNode tmp = head.next;
                 head.next = cur;
                 cur = head;
                 head = tmp;
             }
             head = cur;
         }
         return head;
     }
}

欢迎各位童鞋指出新的想法,我也可以学习学习各位大神的解答。附上执行结果,第一次遇见这样的执行效果,心里美滋滋的。哈哈!

程序执行结果图

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值