1. 程式人生 > >LeetCode:19. 刪除連結串列的倒數第N個節點

LeetCode:19. 刪除連結串列的倒數第N個節點

1、題目描述

給定一個連結串列,刪除連結串列的倒數第 個節點,並且返回連結串列的頭結點。

示例:

  給定一個連結串列: 1->2->3->4->5, 和 n = 2.

  當刪除了倒數第二個節點後,連結串列變為 1->2->3->5.

說明:

給定的 n 保證是有效的。

進階:

你能嘗試使用一趟掃描實現嗎?

2、題解

2.1、解法一

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:

    def __init__(self):
        self.h = None
        self.num = 0

    def add(self, val):
        if self.h == None:
            self.h = ListNode(val)
            self.num += 1
            return

        node = self.h
        while node.next:
            node = node.next

        node.next = ListNode(val)
        self.num += 1
    
    def get_length(self,head):
        node = head
        if head == None:
            return 0
        count = 0
        while node:
            count += 1
            node = node.next
        return count

    def remove(self,head,n):
        node = head
        prev = node
        count = 0
        ret_list = []
        while node:
            print(":",node.val)
            if count == n:
                prev.next = node.next
                self.num -= 1
            else:
                ret_list.append(node.val)
                prev = node
            node = node.next
            count += 1

        return ret_list

    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        print(self.get_length(head))
        ret = self.remove(head,self.get_length(head) -n)
        return ret