zoukankan      html  css  js  c++  java
  • leetcode19 Remove Nth Node From End of List

     1 """
     2 Given a linked list, remove the n-th node from the end of list and return its head.
     3 Example:
     4 Given linked list: 1->2->3->4->5, and n = 2.
     5 After removing the second node from the end, the linked list becomes 1->2->3->5.
     6 """
     7 """
     8 看到这道题想法是用遍历两遍链表,第一次找出删除点,第二次删除
     9 其实可以注意 间距这个条件,用两个指针,一次遍历就能完成
    10 """
    11 """
    12 Time Limit Exceeded
    13 Last executed input
    14 [1]
    15 1
    16 """
    17 class ListNode:
    18     def __init__(self, x):
    19         self.val = x
    20         self.next = None
    21 
    22 class Solution1:
    23     def removeNthFromEnd(self, head, n):
    24         total = 0
    25         p = head
    26         q = head
    27         while p:
    28             total += 1
    29             p =  p.next
    30         step = total - n -1
    31         while step:
    32             if q:
    33                 q = q.next
    34                 step -= 1
    35         q.next = q.next.next
    36         return head
    37 
    38 class ListNode:
    39     def __init__(self, x):
    40         self.val = x
    41         self.next = None
    42 
    43 class Solution2:
    44     def removeNthFromEnd(self, head, n):
    45         pre = head
    46         cur = head
    47         # for _ in range(n):
    48         #     cur = cur.next
    49         # bug  注意for 和 while循环的使用
    50         while n:            #利用间距 可以省去一次循环
    51             cur = cur.next
    52             n -= 1
    53         if cur == None:  # 需要删除的节点为第一个节点时,即返回第二个节点为头节点的链表
    54             return head.next
    55         while cur.next:
    56             cur = cur.next
    57             pre = pre.next
    58         pre.next = pre.next.next
    59         return head
  • 相关阅读:
    fern没有扫描到任何ap
    kali软件的必须知道的那些事
    我的kali学习计划
    arping 自己
    kali密码破解
    kali目录修改
    我的电脑网络不通了
    收藏链接的正确方法
    maltego的 卡 慢 没反应 的问题解决方法
    git报错 failed: The TLS connection was non-properly terminated.
  • 原文地址:https://www.cnblogs.com/yawenw/p/12274263.html
Copyright © 2011-2022 走看看