File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed
data_structures/3_LinkedList Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Node :
2
+ def __init__ (self , data = None , next = None , prev = None ):
3
+ self .data = data
4
+ self .next = next
5
+ self .prev = prev
6
+
7
+ class LinkedList :
8
+ def __init__ (self ):
9
+ self .head = None
10
+
11
+
12
+ def print_forward (self ):
13
+ if self .head is None :
14
+ print ("Linked list is empty" )
15
+ return
16
+ itr = self .head
17
+ llstr = ''
18
+ while itr :
19
+ llstr += str (itr .data )+ ' --> ' if itr .next else str (itr .data )
20
+ itr = itr .next
21
+ print (llstr )
22
+
23
+ def print_backward (self ):
24
+ if self .head is None :
25
+ print ("Linked list is empty" )
26
+ return
27
+ itr = self .head
28
+ llstr = ''
29
+ while itr .next :
30
+ itr = itr .next
31
+
32
+ while itr :
33
+ llstr += str (itr .data )+ ' --> ' if itr .prev else str (itr .data )
34
+ itr = itr .prev
35
+ print (llstr )
36
+
37
+ def insert_at_begining (self , data ):
38
+ node = Node (data , self .head )
39
+ if self .head :
40
+ self .head .prev = node
41
+
42
+ self .head = node
43
+
44
+ def insert_at_end (self , data ):
45
+ if self .head is None :
46
+ self .head = Node (data , None )
47
+ return
48
+
49
+ itr = self .head
50
+
51
+ while itr .next :
52
+ itr = itr .next
53
+
54
+ itr .next = Node (data , None , itr )
55
+
56
+ def insert_values (self , data_list ):
57
+ self .head = None
58
+ for data in data_list :
59
+ self .insert_at_end (data )
60
+
61
+ if __name__ == '__main__' :
62
+ ll = LinkedList ()
63
+ ll .insert_values (["banana" ,"mango" ,"grapes" ,"orange" ])
64
+
65
+ ll .print_forward ()
66
+ ll .print_backward ()
You can’t perform that action at this time.
0 commit comments