zoukankan      html  css  js  c++  java
  • leetcode——25. K 个一组翻转链表

    用栈做:

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def reverseKGroup(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            dummy=ListNode(0)
            p=dummy
            while True:
                count=k
                stack=[]
                tmp=head
                while count and tmp:
                    stack.append(tmp)
                    tmp=tmp.next
                    count-=1
                if count:
                    p.next=head
                    break
                while stack:
                    p.next=stack.pop()
                    p=p.next
                p.next=tmp
                head=tmp
            return dummy.next
    执行用时 :32 ms, 在所有 python 提交中击败了95.97%的用户
    内存消耗 :13.2 MB, 在所有 python 提交中击败了44.26%的用户
     
     
    ——2019.10.31
     

    public ListNode reverseKGroup(ListNode head, int k) {
            ListNode dummy = new ListNode(0);
            dummy.next = head;
    
            ListNode pre = dummy;
            ListNode end = dummy;
    
            while (end.next != null) {
                for (int i = 0; i < k && end != null; i++) end = end.next;
                if (end == null) break;
                ListNode start = pre.next;
                ListNode next = end.next;
                end.next = null;
                pre.next = reverse(start);
                start.next = next;
                pre = start;
    
                end = pre;
            }
            return dummy.next;
        }
    
        private ListNode reverse(ListNode head) {
            ListNode pre = null;
            ListNode curr = head;
            while (curr != null) {
                ListNode next = curr.next;
                curr.next = pre;
                pre = curr;
                curr = next;
            }
            return pre;
        }

     自己还是没能做出来。

    ——2020.7.14

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    左眼右眼
    Mac 的“任务管理器” —— 活动监视器
    [分享] VIM 常用命令及游戏练级
    iOS 7 如何关闭已打开的应用(App)
    iPhone 如何设置彩信 ?
    JavaScript —— attachEvent 方法的使用
    习惯&感恩
    MySQL 基础 备份和恢复
    Python 数据结构 树
    Python 正在表达式
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11774167.html
Copyright © 2011-2022 走看看