zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    flask之闪现
    对于Flask中蓝图的理解
    flask中的CBV和FBV
    Flask之基本使用与配置
    Flask
    Flask-信号(blinker)
    flask-migrate
    Flask WTForms的使用和源码分析 —— (7)
    mac下卸载jdk
    RabbitMQ五种消息队列学习(三)–Work模式
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4350755.html
Copyright © 2011-2022 走看看