Sharw
Sharw

Reputation: 81

Deleting the last element in my linked list

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?

Upvotes: 0

Views: 3724

Answers (3)

saurabh T
saurabh T

Reputation: 1

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)

Upvotes: 0

aghast
aghast

Reputation: 15310

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

Upvotes: 0

Garrett R
Garrett R

Reputation: 2662

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

Upvotes: 3

Related Questions