|
| 1 | +/** |
| 2 | + * Given a singly linked list L0 -> L1 -> … -> Ln-1 -> Ln. |
| 3 | + * Rearrange the nodes in the list so that the new formed list is : L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 … |
| 4 | + * Example: |
| 5 | + * Input: 1 -> 2 -> 3 -> 4 |
| 6 | + * Output: 1 -> 4 -> 2 -> 3 |
| 7 | + * Input: 1 -> 2 -> 3 -> 4 -> 5 |
| 8 | + * Output: 1 -> 5 -> 2 -> 4 -> 3 |
| 9 | + */ |
| 10 | + |
| 11 | +#include <iostream> |
| 12 | + |
| 13 | +struct Node { |
| 14 | + int data; |
| 15 | + Node * next; |
| 16 | + Node( int d ) |
| 17 | + : data{ d }, next{ nullptr } { } |
| 18 | +}; |
| 19 | + |
| 20 | +void printList( Node * node ) |
| 21 | +{ |
| 22 | + while( node ) { |
| 23 | + std::cout << node->data << "-->"; |
| 24 | + node = node->next; |
| 25 | + } |
| 26 | + std::cout << "NULL" << std::endl; |
| 27 | +} |
| 28 | + |
| 29 | +void reverse( Node * & head ) |
| 30 | +{ |
| 31 | + Node * nextNode = nullptr; |
| 32 | + Node * newHead = nullptr; |
| 33 | + Node * curr = head; |
| 34 | + while( curr ) { |
| 35 | + nextNode = curr->next; |
| 36 | + curr->next = newHead; |
| 37 | + newHead = curr; |
| 38 | + curr = nextNode; |
| 39 | + } |
| 40 | + head = newHead; |
| 41 | +} |
| 42 | + |
| 43 | +Node * middleNode( Node * head ) |
| 44 | +{ |
| 45 | + Node * slowPtr = head; |
| 46 | + Node * fastPtr = head; |
| 47 | + while( fastPtr && fastPtr->next ) { |
| 48 | + fastPtr = fastPtr->next->next; |
| 49 | + slowPtr = slowPtr->next; |
| 50 | + } |
| 51 | + return slowPtr; |
| 52 | +} |
| 53 | + |
| 54 | +void rearrange( Node * & head ) |
| 55 | +{ |
| 56 | + //step 1 split the list in two lists first half and second half |
| 57 | + Node * midNode = middleNode(head); |
| 58 | + Node * itr1 = head; |
| 59 | + Node * itr2 = midNode->next; |
| 60 | + midNode->next = nullptr; |
| 61 | + |
| 62 | + //step 2 reverse the second half |
| 63 | + reverse(itr2); |
| 64 | + |
| 65 | + //step 3 - merge the alternate nodes of these two list in one list. |
| 66 | + //dummy node as head |
| 67 | + Node * newHead = new Node(0); |
| 68 | + Node * curr = newHead; |
| 69 | + while( itr1 || itr2 ) { |
| 70 | + if (itr1) { |
| 71 | + curr->next = itr1; |
| 72 | + curr = curr->next; |
| 73 | + itr1 = itr1->next; |
| 74 | + } |
| 75 | + if (itr2) { |
| 76 | + curr->next = itr2; |
| 77 | + curr = curr->next; |
| 78 | + itr2 = itr2->next; |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + //update the head |
| 83 | + head = newHead->next; |
| 84 | +} |
| 85 | + |
| 86 | + |
| 87 | +int main() |
| 88 | +{ |
| 89 | + Node *head = new Node(1); |
| 90 | + head->next = new Node(2); |
| 91 | + head->next->next = new Node(3); |
| 92 | + head->next->next->next = new Node(4); |
| 93 | + head->next->next->next->next = new Node(5); |
| 94 | + printList(head); |
| 95 | + rearrange(head); |
| 96 | + printList(head); |
| 97 | + return 0; |
| 98 | +} |
0 commit comments