zoukankan      html  css  js  c++  java
  • 【leetcode】92:反转链表 II

    题目如下:

     本题目的精华在于不要用一个for循环遍历整个linked list,而是使用两个for或者三个for对同一个linked list从前到后进行遍历,同样也只遍历O(the number of nodes)=O(N)次,我尝试过仅使用一个while循环来写,虽然也是o(n),但是在穿针引线,也就是处理表头和表尾,left左边的元素和right右边的元素和中间反转链表需要进行分类讨论,比较麻烦,因为有可能遇到反转链表的左边或者没有元素的情况,因此使用两个while分别遍历整个linked list:

    代码如下:

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    class Solution(object):
        def reverseBetween(self, head, left, right):
            count = 1
            dummy = ListNode(0)
            dummy.next = head
            pre = dummy
            while pre.next and count < left:
                pre = pre.next
                count += 1
            cur = pre.next
            tail = cur
            while cur and count <= right:
                nxt = cur.next
                cur.next = pre.next
                pre.next = cur
                tail.next = nxt
                cur = nxt
                count += 1
            return dummy.next

    得解!

  • 相关阅读:
    SQL Server创建表
    SQL Server创建数据库
    SQL Server创建索引
    SQL Server创建视图
    SQL Server创建存储过程
    SQL Server创建触发器
    Unity3D与VS2008结合,加快Unity3D C#开发!
    c#哈希表的用法
    长沙做网站公司解密如何编写高效率的SQL语句
    高效SQL语句必杀技
  • 原文地址:https://www.cnblogs.com/geeksongs/p/15212807.html
Copyright © 2011-2022 走看看