Lecture 31 Singly Linked List III

We'll have more methods used in the singly linked list to be covered in this lecture.

1. Remove any duplicate items in a singly linked list



Whenever the curNode pointer get updated, it will do a quick check to see if 'curNode.data' is already in the dictionary. If it is not, then add this entry into the dictionary. If it is, then do prev.next = curNode.next and cuNode = None to remove the curNode.

Try to implement it by yourself without looking at the example code below:



Make sure you understand the highlighted comment.

2. Print the nth node from the last

The method is to print the data stored in the nth node from the last node. For example, 1->2->3->4->5, in which '4' is the 2nd data from the last node.

The strategy to make this happen is I use the 'len_iterative' method we did before to get the length first. Then we use the length-1 as the distance between the first node to the last node. The nth node from the last node is actually when the distance between the curNode and the last node is n-1, which is when 'length -1' becomes 'n-1' , then you reaches the nth node from the last.

We can implement it in this way: (I put a little bug in the code. Please fix it and verify it using your examples)



3. Print the occurences of a specific data in a singly linked list

The following code can implement this method if you get the bug fixed.



4. Rotate a singly linked list after node 'k'.

'Rotate' here means move all the nodes after node 'k' to the front of the linked list. To do this, we set up two pointers starting at the head pointer first, then move p to the kth node in the list, move q to the end of the list.

To initiate the p and the q pointer:



Then move them to the specific locations in the list. In this case, let's say k=2:



Now, let's 'rotate' it:



To implement this method, the example code is showed below (there is a little bug in the code for you to fix):



5. Move the tail node to the front

We'll implement this using two pointers, one is the 'secondLast' node pointer, the other one is the 'lastNode' node pointer.



Once the two pointers reaches their expected location, we start do the modification to the original list:



To implement this method, I have the following code for you to fix:








Tasks:

1. Code up these 5 methods for your singly linked list class, fix the bugs if necessary.