• Reverse Nodes in k-Group


    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

    思路:

      很简单的翻转链表而已,把图画明白了就可以了。

    我的代码:

    public class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            ListNode dummy = new ListNode(-1);
            dummy.next = head;
            int n = 0;
            while(head != null)
            {
                head = head.next;
                n++;
            }
            if(n < k) return dummy.next;
            ListNode pre = dummy;
            ListNode curpre = dummy.next;
            ListNode cur = curpre.next;
            for(int i = 0; i < n/k; i++)
            {
                for(int cnt = 1; cnt < k; cnt++)
                {
                    ListNode next = cur.next;
                    curpre.next = cur.next;
                    cur.next = pre.next;
                    pre.next = cur;
                    cur = next;
                }
                pre = curpre;
                curpre = curpre.next;
                if(curpre != null)
                    cur = curpre.next;
            }
            return dummy.next;
        }
    }
    View Code
  • 相关阅读:
    火柴排队sol
    国王游戏sol
    子串sol
    跳石头
    解方程sol
    花匠sol
    字符串整理
    计算系数
    矩阵取数游戏sol
    8.2_java_28
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4350755.html
Copyright © 2020-2023  润新知