Linked List in Python

  • Working on building a generic Linked List in Python from the Linked List article at CodeFellows.

    Here it is...

    class Node(object):
        def __init__(self, data):
   = data
            self.nextNode = None
    class linkedList(object):
        def __init__(self, head=None):
            self.head = head
        def insert(self, node):
            if not self.head:
                self.head = node
                # set new nodes pointer to old thread
                node.nextNode = self.head
                # reset head to new node
                self.head = node
        def search(self, lList, Node):
            if self.head == Node:
                return self.head
                if lList.head.nextNode:
          , Node)
                    raise ValueError("Node not in Linked List")
        def size(self):
            current = self.head
            size = 0
            while current is not None:
                size += 1
                current = current.nextNode
            return size
        def delete(self, node):
            if self.size() == 0:
                raise ValueError("List is empty")
                current = self.head
                previous = None
                found = False
                while not found:
                    if current == node:
                        found = True
                    elif current is None:
                        raise ValueError("Node not in Linked List")
                        previous = current
                        current = current.nextNode
                if previous is None:
                    self.head = current.nextNode
                    previous.nextNode = current.nextNode

  • Here is the code for using the above list to make a LinkedList and to insert some test data:

    myList = linkedList()
    for x in range(1,10):
        y = Node(x)

Log in to reply