singly linked list in python remove function

class Node:
    def __init__(self, key=None):
        self.key = key
        self.next = None
    def __str__(self):
        return str(self.key)

class SinglyLinkedList:
    def __init__(self):
        self.head = None
        self.size = 0

    def __len__(self):
        return self.size

    def printList(self):
        v = self.head
        while(v):
            print(v.key, "->", end=" ")
            v = v.next
        print("None")


    def pushFront(self, key):
        new_node = Node(key)
        new_node.next = self.head
        self.head = new_node            
        self.size += 1

    def pushBack(self, key):
        new_node = Node(key)
        if self.size == 0:  # empty list --> new_node becomes a head!
            self.head = new_node
        else:
            tail = self.head
            while tail.next != None:    # follow links until tail
                tail = tail.next
            tail.next = new_node
        self.size += 1
    def popFront(self): 
        key = None
        if len(self) > 0:
            key = self.head.key
            self.head = self.head.next
            self.size -= 1
        return key
    def popBack(self):
        if self.size == 0:  # empty list (nothing to pop)
            return None, None
        else:
            previous, current = None, self.head
            while current.next != None:
                previous, current = current, current.next   
            tail = current
            key = tail.key
            if self.head == tail:   # 또는 if previous == None:
                self.head = None
            else:
                previous.next = tail.next   # previous가 새로운 tail이 됨!
            self.size -= 1
            return key
    def search(self, key):
        v = self.head
        while v:
            if v.key == key:
                return v
            v = v.next
        return None     # key 값을 저장된 노드 리턴. 없으면 None 리턴

    def remove(self, v):
        if self.head == None or v == None:
            return
        else: 
            if v == self.head:
                self.head=v.next
            else:
                prev == self.head
                while prev != None:
                    prev == prev.next
                prev.next = v.next
                del v

    def size(self):
        return self.size

    L = SinglyLinkedList()
    while True:
        cmd = input().split()
        if cmd[0] == "pushFront":
            L.pushFront(int(cmd[1]))
            print(int(cmd[1]), "is pushed at front.")
        elif cmd[0] == "pushBack":
            L.pushBack(int(cmd[1]))
            print(int(cmd[1]), "is pushed at back.")
        elif cmd[0] == "popFront":
            x = L.popFront()
            if x == None:
                print("List is empty.")
            else:
                print(x, "is popped from front.")
        elif cmd[0] == "popBack":
            x = L.popBack()
            if x == None:
                print("List is empty.")
            else:
                print(x, "is popped from back.")
        elif cmd[0] == "search":
            x = L.search(int(cmd[1]))
            if x == None:
                print(int(cmd[1]), "is not found!")
            else:
                print(int(cmd[1]), "is found!")
        elif cmd[0] == "remove":
            x = L.search(int(cmd[1]))
            if L.remove(x):
                print(x.key, "is removed.")
            else:
                print("Key is not removed for some reason.")
        elif cmd[0] == "printList":
            L.printList()
        elif cmd[0] == "size":
            print("list has", len(L), "nodes.")
        elif cmd[0] == "exit":
            print("DONE!")
            break
        else:
            print("Not allowed operation! Enter a legal one!")

I am trying to make singly linked list in Python. My code is working quite well, but remove() function only itself is not working at all. I understand what I have to do in remove is to make two cases, one is when value is head node, and the other is when it's not. I tried my best, but still I have no idea where my code has gone wrong. Can you pleas help me?

Upvotes: 0

Views: 255

Answers (1)

Devansh Soni
Devansh Soni

Reputation: 771

I've modified remove() function and it worked:

def remove(self, v):
    if self.head == None or v == None:
        return False
    else:
        if v == self.head:
            self.head = v.next
        else:
            prev = self.head
            while prev.next != v:
                prev = prev.next
            prev.next = v.next
            del v
        return True

Hope this helps :)

See this Screenshot here: Screenshot

Upvotes: 0

Related Questions