Swap two adjacent elements by adjusting only the links (and not the data) using:
ID: 3651846 • Letter: S
Question
Swap two adjacent elements by adjusting only the links (and not the data) using:a. Singly Linked Lists.
b. Doubly Linked Lists.
For example:
n = node
Say you had n1, n2, n3 and you had a pointer p pointing at n2.
The Swap routine of this should make it become n3, n2, n1.
For clarification purposes only:
Say you had n1, n2, n3, n4, n5 and you had a pointer p pointing at n3.
The Swap routine of this should make it become n1, n4, n3, n2, n5.
Explanation / Answer
void swap (struct list **head) { struct list *node1 = *head; struct list *node2 = node1 ? node1->next : NULL; // handle degenerate cases if (!node2) { // no elements or only one element on the list // nothing to do... return; } // fix-up list head to what will be the new first node on list *head = node2; // while there are at least 2 more elements to be swapped while (node1 && node2) { struct list* node3 = node2->next; // get a pointer to the node that will be the remainder of the // list after the remainder of the list is processed. // // This will be NULL, node3, or 'node4' depending on whether // there are 0 , 1 or 2+ nodes following node1 and node2 struct list* remainder = (node3 && node3->next) ? node3->next : node3; node1->next = remainder; node2->next = node1; // prepare pointers to the next two nodes to be swapped node1 = node3; node2 = node3 ? node3->next : NULL; } return; }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.