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

    得解!

  • 相关阅读:
    4
    把URL传递参数转变成自定义实体方法
    【转载】C#后台声明式验证,远离if验证
    判断访问浏览器版本
    用属性动画模仿展开菜单
    N个数随机相加得出固定值的排列组合
    css3--box-shadow
    学习仅仅是靠意志力吗
    cmd 输入php出错
    切图注意事项
  • 原文地址:https://www.cnblogs.com/geeksongs/p/15212807.html
Copyright © 2011-2022 走看看