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

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    jQuery基础及选择器
    JavaScript面向对象
    JavaScript操作DOM
    JavaScript Bom对象
    jquery内容
    jQuery基础
    正则表达式
    表单校验
    使用jQuery操作DOM
    jQuery中的动画
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11774167.html
Copyright © 2011-2022 走看看