11
2- #linked list has nodes - each node has a value and a pointer to next node- who comes next.
2+ #each node should know what comes before it and what come after it
33class node :
44 def __init__ (self ,value ):
55 self .value = value
6- self .next = None #None means empty we are not yet pointing to another node yet
7- pass
8- class linkedlist :
6+ self .next = None
7+ self .previous = None #to implement a 0(1) we need a implement a double linked list to access previous.
8+
9+ #for O(1), track both ends
10+ class LinkedList :
911 def __init__ (self ):
10- self .head = None #head is the first element of a linked list
12+ self .head = None
13+ self .tail = None
1114
12- def append (self ,value ):
15+ def push_head (self ,value ):
1316 new_node = node (value )
14- if self .head is None :
15- self .head = new_node
16- return
17- #creating a temperory pointer current to move forward safely
18- current = self .head #makes a copy of first head node with current being our temp pointer
19- while current . next is not None : # head > next > next > next >
20- current = current . next
17+ if self .head is None :
18+ self .head = self . tail = new_node
19+ return new_node
20+
21+ new_node . next = self .head
22+ self . head . previous = new_node
23+ self . head = new_node
2124
22- current .next = new_node
25+ return new_node
26+
27+ #Remove last node
28+ def pop_tail (self ):
29+ if self .tail is None :
30+ return None
31+
32+ removed = self .tail
33+ #checking for 1 elemt
34+ if self .head == self .tail :
35+ self .head = self .tail = None
36+ return removed .value
37+
38+ #Greater than 1 element, move tailpointer to previos
39+ self .tail = self .tail .previous
40+ self .tail .next = None #cutting link to old tail
41+ return removed .value
42+
43+ def remove (self , node ):
44+ if node .previous is not None : #fixing previous link
45+ node .previous .next = node .next
46+ else :
47+ # removing the head
48+ self .head = node .next
2349
24- def print_list (self ):
25- current = self .head
26- while current is not None :
27- print (current .value )
28- current = current .next
29- ll = linkedlist ()
30- ll .append (10 )
31- ll .append (20 )
32- ll .append (30 )
33- ll .print_list ()
50+ if node .next is not None :
51+ node .next .previous = node .previous
52+ else :
53+ # removing the tail
54+
55+ self .tail = node .previous
0 commit comments