Lecture
30 Singly Linked List II
We'll
continue on working out the methods may appear in a singly linked list
Class.
1. Delete a node at a specific position
If the position is at '0', you need to remove the head node and assign
the '.next' pointer to the head pointer, and then assgin None to the
first node.
It may look like this:
This
is pretty similar to the delete method based on a specific 'key'. The
main difference here is using a counter when the pionter scans through
the items in the list to find the requested position.
2. Length of the linked list
Use an interative way:
This
is very straightforward. First, duplicate the head pointer, then move
the duplicate to the right side of the list until reaches the end.
Second, set up a counter to count how many interations have been
involved through this travel. The final value stored in the counter
will be the length of the list.
Or use a recursive way:
After you instatiate the lst = linkedList(), you can invoke this method by: lst.len_recursive(lst.head)
3. Swap nodes
There are three cases to be discussed for this swap operation:
1) The two nodes to be swapped are the same (given that the nodes in the list must be unique), then don't do anything.
This case is easy. If the two given 'keys' are the same, just report 'The two nodes are the same node, they cannot be swapped'.
2) One of the nodes to be swapped is the head node.
The schematic to show this swapping operation is as follows:
To
take the node out of the link, we need to keep track of the 'Previous
node' and the 'Current Node'. Set up two pointers for each node -
'prev1, curNode1' and 'prev2, curNode2'. Keep moving them to the right
side of the list at the same time until the find the key. One they are
found, just connect head to head and tail to tail for these two nodes.
The code will be present in Section 3).
3) None of them are the head node.
If
none of the 'current nodes' are the head node, the only difference is
we don't need to take care of the 'head pointer'. The schematic is
showed below:
The code for the swap operation is:
4. Reverse a linked list
To
reverse a linked list uses the same strategy of keeping track of both
the previous node and the current node and just flip the '.next'
pointer from pointing to the right to pointing to the left instead.
This is how you can implement it:
Test these methods on your side.
Tasks:
1. Implement the 'Delete', 'Length', 'Swap', and 'Reverse' methods
for your linkedList Class. Including your test code at the bottom of
the script.