Deleting the last element in my linked list

☆樱花仙子☆ 提交于 2019-12-08 12:35:48

问题


I've created a list using only the Node class

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)

I've intialized the list and the last Node is None. I'm trying to delete this node but don't know how to?


回答1:


One good way to do this is to keep track of the previous node and the current node, and then when you reach the end of the list, set the next of the previous to None.

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



回答2:


You'll probably want a List class to manage your nodes.

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



回答3:


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

Add this method in your linked list class which would look like

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


来源:https://stackoverflow.com/questions/35329760/deleting-the-last-element-in-my-linked-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!