Splitting Linked List at a given node into two sublists

Dec 10, 2018 at 4:01am
Hello, I am in need of some help with this problem given to me here. I don't even know where to start, so if someone could help me get the ball rolling that would be greatly appreciated. Or if you could provide me with some of the definition of divideAt, that would be greatly helpful. Thank you.


Add the following operation to the class linkedListType:

 
void divideAt(linkedListType<Type> &secondList, const Type& item);


//Divide the list at the node with the info item into two sublists.
Postcondition: first and last point to the first and last nodes of the first sublist.secondList.first and secondList.lastpoint to the first and last nodes of the second sublist.
Consider the following statements:
1
2
unorderedLinkedList<int> myList; 
unorderedLinkedList<int> otherList;

Suppose myList points to the list with the elements 34 65 18 39 27 89 12 (in this order). The statement:
 
myList.divideAt(otherList, 18);

divides myList into two sublists: myList points to the list with the elements 34 65, and otherList points to the sublist with the elements 18 39 27 89 12.


Dec 10, 2018 at 4:32am
Assuming:
linkedListType contains a link pointer called 'next', and a Type called 'value'.
unorderedLinkedList contains a pointer to linkedListType called 'head'.

1
2
3
4
5
6
linkedListType *node = head;
linkedListType *prev = nullptr;
while ( node && node->value != item ) {
    prev = node;
    node = node->next;
}

This gets you to the split point.

In the general case, you do
1
2
prev->next = nullptr;  // terminate the first list
secondList.head = node;  // the start of the new list 


I'll leave you to solve the various edge cases such as
- first list starts empty
- first list ends up empty
- item isn't found
- some others perhaps.

Dec 10, 2018 at 4:47am
Okay, I think I got it now. By the way, under a while loop is one if/else duo considered like one statement? Because I am looking at code where the while statement has no brackets {} and it has an if/else under it like if its one line of code.
Dec 10, 2018 at 4:55am
If you mean like this, then it's one statement.
1
2
3
while ( foo )
    if ( bar ) foo = true;
    else foo = false;

Dec 10, 2018 at 5:48am
What about this:
1
2
3
4
5
6
7
8
while (current != first && !found)
                    if (current->info == item)
                        found = true;
                    else
                    {
                        trailCurrent = current;
                        current = current->link;
                    }
Dec 10, 2018 at 8:42am
Yep, still one.
Dec 10, 2018 at 4:23pm
while ( foo = bar); //granted the compiler will warn but this is the intended loop.

Topic archived. No new replies allowed.