Wednesday, 10 May 2017

Python Program to create a Singly Linked List

Python program is given below to create a singly Linked List. This program contains two classes first is class Node and the second is class LinkedList, Both the classes are discussed below.


Node Class:
Each node object must hold at least two pieces of information. First the data item in the node and the second is reference to the next node. A refrence to None means here that there is no next node. Note in the constructor that a node is initially created with next to None.

LinkedList class:
Whenever an object of LinkedList class is created it will initialize to none i.e there is no node in linked list. you can look at self.head=None. Whenever you will add a node in the LinkedList. First insert() method in the LinkedList will check if there a node is already created or not. If not then it will assign the head node to current else it will go forward till no node is found.

PROGRAM:

class Node:
 def __init__(self,data,next=None):
  self.data=data
  self.next=None

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

 def insert(self,data):
  if(self.head==None):
   n=Node(data)
   self.head=n
   return
  else:
   current=self.head
   while(current.next!=None):
    current=current.next
   current.next=Node(data)
   return
 def printing(self):
  if(self.head==None):
   print "Linked List is empty"
  else:
   current=self.head
   while(current!=None):
    print current.data,
    current=current.next
myLinkList=LinkedList()
myLinkList.insert(18)
myLinkList.insert(20)
myLinkList.insert(56)
myLinkList.insert(50)
print("\n\nThe created Singly Linked List is: \n\n")
myLinkList.printing()
print("\n\n")


OUTPUT:




See also: Python Program to insert node at any position in the singly Linked List


EmoticonEmoticon