zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):019-Remove Nth Node From End of List

    题目来源:

    https://leetcode.com/problems/remove-nth-node-from-end-of-list/


    题意分析:

      这道题是给定一个链表,删除倒数第n个节点。提醒,1.输入的链表长度必然大于n,2.尽量通过访问一次就得到结果。


    题目思路:

      这道题的问题在于如何找到倒数第n个节点。由于只能访问一次,所以可以建立两个链表,tmp1和tmp2。tmp1先访问第一个到n个节点。这时候,tmp2从0开始访问。等tmp1访问结束的时候,tmp2刚好访问到倒数第n个节点。


    代码(python):

     1 # Definition for singly-linked list.
     2 # class ListNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution(object):
     8     def removeNthFromEnd(self, head, n):
     9         """
    10         :type head: ListNode
    11         :type n: int
    12         :rtype: ListNode
    13         """
    14         ans = ListNode(0);
    15         ans.next = head
    16         tmp1 = ans
    17         tmp2 = ans
    18         i = 0
    19         while i < n:
    20             tmp1 = tmp1.next
    21             i += 1
    22         while tmp1.next:
    23             tmp1 = tmp1.next
    24             tmp2 = tmp2.next
    25         tmp2.next = tmp2.next.next
    26         return ans.next
    27         
    View Code

    转载请注明出处:http://www.cnblogs.com/chruny/p/4844007.html

  • 相关阅读:
    (转载)构建public APIs与CORS
    SpringMVC 参数注入
    java删除文件夹
    idea 自动提示生成 serialVersionUID
    JSP自定义tag
    gradle中使用嵌入式(embedded) tomcat, debug 启动
    spring in action 4th --- quick start
    Date, TimeZone, MongoDB, java中date的时区问题
    spring boot 添加拦截器
    HTTP status code
  • 原文地址:https://www.cnblogs.com/chruny/p/4844007.html
Copyright © 2011-2022 走看看