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.
k is a positive integer and is less than or equal to the length of the linked 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

分析:

知道了翻转链表的通用写法之后,解这一题其实就是循环翻转的过程(知道最后一个group长度不足)。
先介绍下翻转链表的写法:


  1. 首先设置一个前置节点,将前置节点的next设置为头节点,以头节点为当前节点,开始循环
  2. 将当前节点的next赋给一个临时节点,然后将当前节点的next指向前置节点,随后依次位移前置节点指针和当前节点指针:前置节点指针指向当前节点,当前节点指针指向临时节点,这样就完成了一次循环
  3. 当前置节点指针指向尾节点时,循环结束
  4. 有个这个翻转函数之后,只要对链表进行循环,当计数长度不k时,指针继续前进;当计数长度到达k时,将头尾节点作为参数传入翻转函数进行翻转,然后重新拼接到原链表中。直至到达链表末尾。


代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
          if(head == null)  
    {  
        return null;  
    }  
    ListNode dummy = new ListNode(0);  
    dummy.next = head;  
    int count = 0;  
    ListNode pre = dummy;  
    ListNode cur = head;  
    while(cur != null)  
    {  
        count ++;  
        ListNode next = cur.next;  
        if(count == k)  
        {  
            pre = reverse(pre, next);  
            count = 0;     
        }  
        cur = next;  
    }  
    return dummy.next;  
    }
    private ListNode reverse(ListNode pre, ListNode end)  
    {  
        if(pre==null || pre.next==null)  
            return pre;  
        ListNode head = pre.next;  
        ListNode cur = pre.next.next;  
        while(cur!=end)  
        {  
            ListNode next = cur.next;  
            cur.next = pre.next;  
            pre.next = cur;  
            cur = next;  
        }  
        head.next = end;  
        return head;  
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值