19. Remove Nth Node From End of List

Posted PolarBearInterest

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了19. Remove Nth Node From End of List相关的知识,希望对你有一定的参考价值。

题目:

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

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

代码:

从链表中删除从右向左数第N个元素,况且只能遍历链表一遍。

所以,需要定义两个指针,相差是N个元素,同时向前遍历,当靠前的元素走到最后的时候,在后面的元素刚好与最后一个元素距离为N,删除即可。

于是:

#Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution(object):
    
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        p = head
        q = head
        if head.next ==None:return []
        for i in range(0,n):
            q = q.next
        if not q : return head.next
        while q.next:
            p = p.next
            q = q.next
        temp = p.next.next
        p.next = temp
        return head
        
if __name__==‘__main__‘:
    arr = [1,2]
    p = ListNode(arr[0])
    head = p
    for i in arr[1:]:
        p.next = ListNode(i)
        p = p.next
    s=Solution()
    q=s.removeNthFromEnd(head,2)
    while q:
        print (q.val)
        q = q.next

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

LC_19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

[LeetCode19]Remove Nth Node From End of List

19. Remove Nth Node From End of List