删除链接列表中的最后一个元素

时间:2016-02-11 02:28:29

标签: python nodes

我仅使用Node类

创建了一个列表
class Node:
def __init__(self, init_data):
    self.data = init_data
    self.next = None

def get_data(self):
    return self.data

def get_next(self):
    return self.next

def set_data(self, new_data):
    self.data = new_data

def set_next(self, new_next):
    self.next = new_next

def __str__(self):
    return str(self.data)

我已经初始化了列表,最后一个节点是None。 我试图删除此节点,但不知道如何处理?

3 个答案:

答案 0 :(得分:2)

执行此操作的一个好方法是跟踪上一个节点和当前节点,然后当到达列表末尾时,将上一个节点设置为无。

prev = None
cur = head
while cur.next is not None:
    prev = cur
    cur = cur.next
if prev: #in case the head is the tail
    prev.next = None

答案 1 :(得分:0)

您可能希望List班级来管理您的节点。

class List:
    def __init__(self):
        self._nodes = None

    def push(self, node):
        node.set_next(self._nodes)
        self._nodes = node
        return self

    def pop(self):
        if self._nodes is None:
            return None

        temp = self._nodes
        self._nodes = temp.get_next()
        return temp

    def __len__(self):
        l = 0
        n = self._nodes
        while n is not None:
            n = n.get_next()
            l += 1
        return l

    def remove(self, node):
        n = self._nodes
        p = None
        while n is not None:
            if n is node:
                p.set_next(n.get_next())
                n.set_next(None)
                return True

            p = n
            n = n.get_next()

        return False

答案 2 :(得分:0)

def del_from_end(self):
    if self.head is None:
        return "No node to delete"
    else:
        current = self.head

        while current.next.next is not None:
            current = current.next
        current.next = None

将此方法添加到链接列表类中,看起来像

class LinkedList():
    def __init__(self, head=None):
        if head == "" or head is None:
            self.head = None
        else:
            self.head = Node(head)