删除方法python的LinkedList实现

时间:2015-09-22 05:36:34

标签: python python-3.x

class LinkedList:
def __init__(self):
    self.head = None

def print_all(self):
    current = self.head
    while current != None:
        print(current.get_data())
        current = current.get_next()

def add(self, item): 
    new = Node(item)
    new.set_next(self.head)
    self.head = new

def remove_from_tail(self):
    #Method to be implemented needs to remove the end item of the linked list by tracking the current viewed item and tracking the previous item and setting the 'next' node field to None.

函数调用的一个例子

my_list = LinkedList()

my_list.add('cat')
my_list.add('bit')
my_list.add('ask')

result = my_list.remove_from_tail()

print('Removed:', result)
my_list.print_all()

预期产出:

Removed: cat
ask
bit

假设Node类由标准约定实现(get_next,set_next,get_data,set_data等)

我一直试图这样做几个小时,但我知道这是一个相对简单的练习,我不知道如何定义remove_from_tail函数。

1 个答案:

答案 0 :(得分:0)

print_all()

捏起基本实现
class LinkedList:
    #[..]

    def print_all(self):
        current = self.head
        while current != None:
            print(current.get_data())
            current = current.get_next()

    #[..]

    def remove_from_tail(self):
        current = self.head

        # Check for an empty list
        if current = None:
            return None

        # Check for an one-item list
        if current.get_next() == None:
            data = current.get_data()
            self.head = None
            return data

        # Multi item list
        while current.get_next():
            previous = current
            current = current.get_next()

        data = current.get_data()
        previous.set_next(None)
        return data

[编辑:哎呀]