Splitting Linked List at a given node into two sublists

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.


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.

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.
If you mean like this, then it's one statement.
1
2
3
while ( foo )
    if ( bar ) foo = true;
    else foo = false;

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;
                    }
Yep, still one.
while ( foo = bar); //granted the compiler will warn but this is the intended loop.

Topic archived. No new replies allowed.