标签:amp 时间复杂度 int @param self problem 复杂 元素 移动
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,当前一个指针到链尾时,返回另一个指针。
需要考虑的问题:
[Lintcode]174. Remove Nth Node From End of List/[Leetcode]
标签:amp 时间复杂度 int @param self problem 复杂 元素 移动
原文地址:https://www.cnblogs.com/siriusli/p/10363766.html