1
+ """The LinkedList code from before is provided below.
2
+ Add three functions to the LinkedList.
3
+ "get_position" returns the element at a certain position.
4
+ The "insert" function will add an element to a particular
5
+ spot in the list.
6
+ "delete" will delete the first element with that
7
+ particular value.
8
+ Then, use "Test Run" and "Submit" to run the test cases
9
+ at the bottom."""
10
+
11
+ class Element (object ):
12
+ def __init__ (self , value ):
13
+ self .value = value
14
+ self .next = None
15
+
16
+ class LinkedList (object ):
17
+ def __init__ (self , head = None ):
18
+ self .head = head
19
+
20
+ def append (self , new_element ):
21
+ current = self .head
22
+ if self .head :
23
+ while current .next :
24
+ current = current .next
25
+ current .next = new_element
26
+ else :
27
+ self .head = new_element
28
+
29
+ def get_position (self , position ):
30
+ """Get an element from a particular position.
31
+ Assume the first position is "1".
32
+ Return "None" if position is not in the list."""
33
+ current = self .head
34
+ if current == None :
35
+ return None
36
+ pos = 1
37
+ while pos < position :
38
+ if current .next == None :
39
+ return None
40
+ current = current .next
41
+ pos += 1
42
+ return current
43
+
44
+ def insert (self , new_element , position ):
45
+ """Insert a new node at the given position.
46
+ Assume the first position is "1".
47
+ Inserting at position 3 means between
48
+ the 2nd and 3rd elements."""
49
+ current = self .head
50
+ pos = 1
51
+ while pos < position - 1 :
52
+ current = current .next
53
+ pos += 1
54
+ new_element .next = current .next
55
+ current .next = new_element
56
+
57
+ def delete (self , value ):
58
+ """Delete the first node with a given value."""
59
+ current = self .head
60
+ if current .value == value :
61
+ if self .head .next :
62
+ self .head = self .head .next
63
+ else :
64
+ self .head = None
65
+ if self .head :
66
+ while current .next :
67
+ if current .next .value == value :
68
+ current .next = current .next .next
69
+ break
70
+ current = current .next
71
+
72
+ # Test cases
73
+ # Set up some Elements
74
+ e1 = Element (1 )
75
+ e2 = Element (2 )
76
+ e3 = Element (3 )
77
+ e4 = Element (4 )
78
+
79
+ # Start setting up a LinkedList
80
+ ll = LinkedList (e1 )
81
+ ll .append (e2 )
82
+ ll .append (e3 )
83
+
84
+ # Test get_position
85
+ # Should print 3
86
+ print ll .head .next .next .value
87
+ # Should also print 3
88
+ print ll .get_position (3 ).value
89
+
90
+ # Test insert
91
+ ll .insert (e4 ,3 )
92
+ # Should print 4 now
93
+ print ll .get_position (3 ).value
94
+
95
+ # Test delete
96
+ ll .delete (1 )
97
+ # Should print 2 now
98
+ print ll .get_position (1 ).value
99
+ # Should print 4 now
100
+ print ll .get_position (2 ).value
101
+ # Should print 3 now
102
+ print ll .get_position (3 ).value
0 commit comments