© Copyright 2012 by Pearson Education, Inc. All Rights Reserved ...
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved ...
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved ...
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
new node’s next, as shown in Figure 18.9b. The size is now increased <strong>by</strong><br />
1 (line 133).<br />
head<br />
current<br />
temp<br />
tail<br />
e 0<br />
next<br />
…<br />
e i<br />
next<br />
A new node<br />
to be inserted<br />
here<br />
e i+1<br />
…<br />
next<br />
None<br />
e<br />
(a) Before a n ew node is inserted.<br />
None<br />
e k<br />
head<br />
current<br />
temp<br />
tail<br />
e 0<br />
next<br />
…<br />
e i<br />
next<br />
e i+1<br />
next<br />
…<br />
e k<br />
None<br />
A new node<br />
is inserted in<br />
the list<br />
e<br />
None<br />
(b) After a new node is inserted.<br />
Figure 18.9<br />
A new element is inserted in the middle of the list.<br />
18.2.2.4 Implementing removeFirst()<br />
The removeFirst() method is to remove the first element from the list.<br />
It can be implemented as follows:<br />
1 def removeFirst(self):<br />
2 if self.__size == 0:<br />
3 return None # Nothing to delete<br />
4 else:<br />
5 temp = self.__head # Keep the first node temporarily<br />
6 self.__head = self.__head.next # Move head to point the next<br />
7 self.__size -= 1 # Reduce size <strong>by</strong> 1<br />
8 if self.__head == None:<br />
9 self.__tail = None # List becomes empty<br />
10 return temp.element # Return the deleted element<br />
Consider two cases:<br />
(1) If the list is empty, there is nothing to delete, so return None<br />
(line 3);<br />
12<br />
© <strong>Copyright</strong> <strong>2012</strong> <strong>by</strong> <strong>Pearson</strong> <strong>Education</strong>, <strong>Inc</strong>. <strong>All</strong> <strong>Rights</strong> <strong>Reserved</strong>.