Linked List

  1. Create a simple linked list of strings "mon"->"tue"->"wed"
  2. Traverse a linked list and print elements of the list
  3. Insert "sun" at the begining
  4. Insert "fri" at the end
  5. Add element "thur" in b/w the nodes
  6. [Now replace the element "thur" by "thu"]
  7. [Count the number of elements in the linked list]
  8. [Search an element in a linked list]
  9. [Link the start-end nodes, form a circular linked list]
  10. [Search an element in the circular liked list]
  11. [Insert an element at random position and count the list]

linkedList() 📁

##prob1 | prob2
class Node:
 def __init__(self, val=None):
  self.val = val
  self.next = None
#node definition

class LinkedList:
 def __init__(self):
  self.head = None
#linkedList definition

llist = LinkedList()
#create an object 'llist'
llist.head = Node("mon")
llist.head.next = e2

e3 = Node("wed")
e2 = Node("tue")
e2.next = e3

llist.printList()

#NOTE:do not include `head` in def
#NOTE:`temp.head` include first element

traverseLinkedList 📁

class LinkedList:
  def __init__(self):
    self.head = None

  def printList(self):
    temp = self.head
    while(temp):
      print(temp.val)
      temp = temp.next
#traversing a linked list
llist.printList()

atBegining 📁

 def atBegin(self, data_i):
  e0 = Node(data_i)
  "Let's update the list"
  temp = self.head
  self.head = e0
  e0.next = temp
llist.atBegin("sun")

atEnd 📁 📁

 def atEnd(self, data):
  en = Node(data)
  temp = self.head
  while(temp.next):
   temp = temp.next
  temp.next = en
 def atEnd(self, data):
  en = Node(data)

  if self.head is None:
   self.head = en
   return
  #base case//only when the list is empty
  temp = self.head
  while(temp.next):
   temp = temp.next
  temp.next = en
llist.atEnd("fri")

Insertion in b/w the nodes 📁

 def inBetween(self, inode, data):
  ei = Node(data)
  ei.next = inode.next
  inode.next = ei
llist.inBetween(e3, "thur")