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

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. 没算清移动次数,要自己画一画才知道。
posted @ 2019-02-12 02:21  siriusli  阅读(85)  评论(0编辑  收藏  举报