Leetcode 19. Remove Nth Node From End of List

来源:互联网 发布:监控客户端软件 编辑:程序博客网 时间:2024/06/05 18:04

题目:

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个offset后从当前位置遍历到链表尾巴,删掉待删结点。返回第一个元素。


# 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
        """
        preHead = ListNode(-1);preHead.next=head
        l = preHead
        for _ in xrange(n):head = head.next
        while head!=None:
            l=l.next;head=head.next
        tmp = l.next
        l.next=l.next.next
        tmp = None
        return preHead.next


0 0
原创粉丝点击