zoukankan      html  css  js  c++  java
  • 19. 删除链表的倒数第N个节点-链表(leetcode)

    收获:

      1.在python中对链表中节点进行操作时:

        a) 从前 我直接 return  head (错误)

        b)现在由于怕 head 会被修改,所以要设  point = Listnode(-1)            return point

      2. 我自己只想出了两遍遍历,收获了一遍遍历的思路:  双指针

        a)  使 fast 与 slow 之间始终隔着 n,以例题为例,n=2,需要保证 fast = 5 时候 slow = 3 , slow.next = slow.next.next 

        b) 我记得之前学C的数据结构,需要借助middle 来传递 .next,like   a = point.next;  point.next = a.next; a.next = None

           不知道在python 里面可以直接使用 slow.next = slow.next.next 

        

    代码1)   用了两次遍历的方法

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None

    class Solution:
        def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
            tail = head
            count = 0
            while tail :
                tail = tail.next 
                count +=1
            print(n)
            n = count - n 
            print(n)
            if n ==0:
                return head.next
            else:
                a = head
                m = n-1
                point = 0
                while point < m:
                    head = head.next 
                    point +=1
                target = head.next
                head.next = target.next
                target.next = None
                return a 
                

     代码2)一次遍历  思路借鉴leetcode官方题解

    # Definition for singly-linked list.
    class ListNode:
        def __init__(self, x):
            self.val = x
            self.next = None

    class Solution:
        def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
            if head.next == None:
                return None

            point = ListNode(-1)
            point.next = head
            fast = slow = point 
            i = 0
            while fast.next:
                fast = fast.next
                i+=1   # 2 3 4-2 5-3
                if i>n:
                    slow = slow.next
            slow.next = slow.next.next
            return point.next
     
    下图链接为
     
  • 相关阅读:
    jQuery函数继承 $.extend, $.fn.extend
    [原创]茗洋AaronYang的 jquery.myselect.js 我的一次前端突破[上]
    EasyUI 的 combotree 加载数据后折叠起来,并且只允许单击子节点的写法
    判断js数组包是否包含某个元素
    JS中 HTMLEncode和HTMLDecode
    Easyui datagrid 特殊处理,记录笔记
    easyui tab上面添加右键菜单
    第三方文本框 在div中显示预览,让指定节点不受外部css影响
    Easyui 让Window弹出居中
    C# txt格式记录时间,时间对比,决定是否更新代码记录Demo
  • 原文地址:https://www.cnblogs.com/ChevisZhang/p/12585100.html
Copyright © 2011-2022 走看看