Skip to main content

Section 28.5 Slicing and Splicing Lists

In SectionΒ 23.14, we saw how to split an array-based list into two parts. It involved creating a new array and then copying data over piece by piece. In a linked list, we can split a list into two parts by just changing a few links. For example, if we have a pointer to the node at which we want to split the list, we can just break the link from that node to the next one and return two new lists: one starting at the head of the original list and ending at that node, and one starting at the next node and ending at the tail of the original list.

Exploration 28.5.1. Splitting a Linked List.

(a)

We start with a linked list and a pointer to the node right before the midpoint:
This list has 4 nodes. The pointer "mid" points to the second node.πŸ”—

(b)

We then make the following changes:
This list’s tail is now the node mid points to. Other list starts at the node after mid and its tail is the original list’s tail. Both lists have two nodes.πŸ”—
The changes are highlighted. They include:
  • other.head is set to the node after mid
  • other.tail is set to this list’s tail
  • mid->next is set to nullptr to break off the two lists
  • this.tail is set to mid
  • The size of each list is updated.
Notice that splitting the list just involves changing a few pointers and updating the size. There would not be any more work to do if our list was 10,000 items long instead of just 4. Assuming we have the midpoint pointer, the split process is \(O(1)\text{.}\)
Of course, if we do not have the midpoint pointer, we will have to create one and move it step by step to the midpoint of the list. This would take \(O(n)\) time. However, especially if the items are large, the constant factor for moving a pointer \(O(n)\) times may be smaller than the constant factor for the \(O(n)\) part of slicing an array-based list, where \(n\) items have to be copied over to a new array.

Exploration 28.5.2. Splicing Linked Lists.

(b)

We then make the following changes:
This list’s tail is now the node mid points to. Other list starts at the node after mid and its tail is the original list’s tail. Both lists have two nodes.πŸ”—
After, the list titled β€œthis” owns all the nodes from both lists.
As with slicing, splicing just involves changing a few pointers and updating the size. Assuming we have tail pointers in the lists, we can do the entire operation in constant time (\(O(1)\)). There is no corresponding easy way to splice together two array-based lists. To merge those, we would need to copy all the items from the second to the first array (and possibly reallocate the array), which would require \(O(n)\) time.

Checkpoint 28.5.1.

Build the logic to merge the contents of other into this. You will not use all the blocks
You have attempted of activities on this page.