File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Node :
2+ def __init__ (self , key ):
3+ self .key = key
4+ self .next = None
5+
6+ class LinkedList :
7+ def __init__ (self ):
8+ self .head = None
9+
10+ def push (self , key ):
11+ node = Node (key )
12+ node .next = self .head
13+ self .head = node
14+
15+ def find_loop (self ):
16+ temp1 = self .head
17+ temp2 = self .head
18+ while temp2 :
19+ print temp2 .key
20+ temp1 = temp1 .next
21+ temp2 = temp2 .next .next
22+ if temp1 == temp2 :
23+ print "Loop found at: " ,temp1 .key
24+ return
25+ def traverse (self ):
26+ print "Traversing"
27+ temp = self .head
28+ while temp :
29+ print temp .key
30+ temp = temp .next
31+
32+ list_ = LinkedList ()
33+ list_ .push (1 )
34+ list_ .push (2 )
35+ list_ .push (3 )
36+ list_ .push (4 )
37+ list_ .push (5 )
38+ list_ .traverse ()
39+ list_ .head .next .next .next = list_ .head
40+
41+ list_ .find_loop ()
42+
Original file line number Diff line number Diff line change @@ -46,13 +46,44 @@ def pop_key(self, key):
4646 prev = temp
4747 temp = temp .next
4848
49+ def delete_linked_list (self ):
50+ print "\n Deleting Linked List"
51+ while self .head :
52+ temp = self .head
53+ self .head = self .head .next
54+ temp = None
55+
56+ def len (self ):
57+ cnt = 0
58+ temp = self .head
59+ while temp :
60+ cnt += 1
61+ temp = temp .next
62+ print "Length: " , cnt
63+
64+ def middle (self ):
65+ print "Middle"
66+ temp1 = self .head
67+ temp2 = self .head
68+ while temp2 .next :
69+ temp2 = temp2 .next .next
70+ temp1 = temp1 .next
71+ print temp1 .key
72+
73+ def count_key (self , key , temp , freq = 0 ):
74+ if not temp :
75+ return freq
76+ if temp .key == key :
77+ freq += 1
78+ return self .count_key (key , temp .next , freq )
79+
4980list_ = LinkedList ()
5081list_ .push (2 )
5182list_ .push (5 )
5283list_ .push (8 )
5384list_ .push (9 )
5485list_ .push (1 )
55- list_ .push (3 )
86+ list_ .push (4 )
5687list_ .push (6 )
5788list_ .push (4 )
5889list_ .push (7 )
@@ -65,6 +96,12 @@ def pop_key(self, key):
6596list_ .pop_key (6 )
6697print "\n "
6798list_ .traverse ()
99+ list_ .len ()
100+ list_ .middle ()
101+ print "Number of Times Key occur: " ,list_ .count_key (4 , list_ .head )
102+ list_ .delete_linked_list ()
103+ list_ .traverse ()
104+ list_ .len ()
68105
69106
70107
You can’t perform that action at this time.
0 commit comments