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

Posted siriusli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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. 没算清移动次数,要自己画一画才知道。









以上是关于[Lintcode]174. Remove Nth Node From End of List/[Leetcode]的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-easy-Nth to Last Node in List Show result

LintCode 174. 删除链表中倒数第n个节点

LintCode Python 简单级题目 174.删除链表中倒数第n个节点

lintcode-easy-Remove Element

Remove Nth Node From End of List

19. Remove Nth Node From End of List