1
+ '''
2
+ - A linked list is similar to an array, it holds values. However, links in a linked list do not have indexes.
3
+ - This is an example of a double ended, doubly linked list.
4
+ - Each link references the next link and the previous one.
5
+ '''
6
+ class LinkedList :
7
+ def __init__ (self ):
8
+ self .head = None
9
+ self .tail = None
10
+
11
+ def insertHead (self , x ):
12
+ newLink = Link (x ) #Create a new link with a value attached to it
13
+ if (self .isEmpty () == True ): #Set the first element added to be the tail
14
+ self .tail = newLink
15
+ else :
16
+ self .head .previous = newLink # newLink <-- currenthead(head)
17
+ newLink .next = self .head # newLink <--> currenthead(head)
18
+ self .head = newLink # newLink(head) <--> oldhead
19
+
20
+ def deleteHead (self ):
21
+ temp = self .head
22
+ self .head = self .head .next # oldHead <--> 2ndElement(head)
23
+ self .head .previous = None # oldHead --> 2ndElement(head) nothing pointing at it so the old head will be removed
24
+ if (self .head == None ):
25
+ self .tail = None
26
+ return temp
27
+
28
+ def insertTail (self , x ):
29
+ newLink = Link (x )
30
+ newLink .next = None # currentTail(tail) newLink -->
31
+ self .tail .next = newLink # currentTail(tail) --> newLink -->
32
+ newLink .previous = self .tail #currentTail(tail) <--> newLink -->
33
+ self .tail = newLink # oldTail <--> newLink(tail) -->
34
+
35
+ def deleteTail (self ):
36
+ temp = self .tail
37
+ self .tail = self .tail .previous # 2ndLast(tail) <--> oldTail --> None
38
+ self .tail .next = None # 2ndlast(tail) --> None
39
+ return temp
40
+
41
+ def delete (self , x ):
42
+ current = self .head
43
+
44
+ while (current .value != x ): # Find the position to delete
45
+ current = current .next
46
+
47
+ if (current == self .head ):
48
+ self .deleteHead ()
49
+
50
+ elif (current == self .tail ):
51
+ self .deleteTail ()
52
+
53
+ else : #Before: 1 <--> 2(current) <--> 3
54
+ current .previous .next = current .next # 1 --> 3
55
+ current .next .previous = current .previous # 1 <--> 3
56
+
57
+ def isEmpty (self ): #Will return True if the list is empty
58
+ return (self .head == None )
59
+
60
+ def display (self ): #Prints contents of the list
61
+ current = self .head
62
+ while (current != None ):
63
+ current .displayLink ()
64
+ current = current .next
65
+ print ()
66
+
67
+ class Link :
68
+ next = None #This points to the link in front of the new link
69
+ previous = None #This points to the link behind the new link
70
+ def __init__ (self , x ):
71
+ self .value = x
72
+ def displayLink (self ):
73
+ print ("{}" .format (self .value ), end = " " )
0 commit comments