码迷,mamicode.com
首页 > 其他好文 > 详细

[Lintcode]174. Remove Nth Node From End of List/[Leetcode]

时间:2019-02-12 09:14:04      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:amp   时间复杂度   int   @param   self   problem   复杂   元素   移动   

174. Remove Nth Node From End of List/19. Remove Nth Node From End of List

  • 本题难度: Easy/Medium
  • Topic: Linked List

Description

Given a linked list, remove the nth node from the end of list and return its head.

Example
Example 1:
Input: list = 1->2->3->4->5->null, n = 2
Output: 1->2->3->5->null

Example 2:
Input: list = 5->4->3->2->1->null, n = 2
Output: 5->4->3->1->null

Challenge
Can you do it without getting the length of the linked list?

Notice
The minimum number of nodes in list is n.

我的代码

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: The first node of linked list.
    @param n: An integer
    @return: The head of linked list.
    """
    def removeNthFromEnd(self, head, n):
        # write your code here
        if head == None:
            return None
        p1, p2 = head, head
        while(n>0):
            p1 = p1.next
            n = n-1
        if p1:
            p1 = p1.next
            while(p1):
                p1 = p1.next
                p2 = p2.next
            p2.next = (p2.next).next
            return head
        else:
            return head.next

思路

(这个题我在面试时遇到过。没有答出来,被同学疯狂嘲笑了一波。
设两个指针,期间相隔n,当前一个指针到链尾时,返回另一个指针。

需要考虑的问题:

  1. 当链表为空时
  2. 除去链头元素时。
  • 时间复杂度 O(n)
  • 出错
  1. 没考虑到特殊情况
  2. 没算清移动次数,要自己画一画才知道。

[Lintcode]174. Remove Nth Node From End of List/[Leetcode]

标签:amp   时间复杂度   int   @param   self   problem   复杂   元素   移动   

原文地址:https://www.cnblogs.com/siriusli/p/10363766.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!