|
| 1 | +/* |
| 2 | + * Problem : Given a linked list, and two data values, x and y. |
| 3 | + * Goal: Swap the nodes of linkedlist by swapping pointers ( and not swapping data) such that nodes with data x will contain y and vice versa. |
| 4 | + * |
| 5 | + */ |
| 6 | + |
| 7 | + |
| 8 | +#include <iostream> |
| 9 | + |
| 10 | + |
| 11 | +struct Node { |
| 12 | + int data; |
| 13 | + Node* next; |
| 14 | + Node(int d) : data{d}, next{nullptr} { } |
| 15 | +}; |
| 16 | + |
| 17 | + |
| 18 | +/**** Algorithm Function ****/ |
| 19 | +void swapSpecial(Node* & head, int x, int y) { |
| 20 | + |
| 21 | + //empty list |
| 22 | + if (head == nullptr) { |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + //nothing to do if both are values are same. |
| 27 | + if ( x == y ) { |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + Node * prevx = nullptr; |
| 32 | + Node * currx = head; |
| 33 | + Node * prevy = nullptr; |
| 34 | + Node * curry = head; |
| 35 | + |
| 36 | + //search for x |
| 37 | + while ( currx && currx->data != x ) { |
| 38 | + prevx = currx; |
| 39 | + currx = currx->next; |
| 40 | + } |
| 41 | + //search for y |
| 42 | + while ( curry && curry->data != y ) { |
| 43 | + prevy = curry; |
| 44 | + curry = curry->next; |
| 45 | + } |
| 46 | + //x or y not found |
| 47 | + if ( currx == nullptr || curry == nullptr ) { |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + //if x is not head |
| 52 | + if ( prevx != nullptr ) { |
| 53 | + prevx->next = curry; |
| 54 | + } else { |
| 55 | + head = curry; |
| 56 | + } |
| 57 | + |
| 58 | + //similarly if y is not head |
| 59 | + if ( prevy != nullptr) { |
| 60 | + prevy->next = currx; |
| 61 | + } else { |
| 62 | + head = curry; |
| 63 | + } |
| 64 | + |
| 65 | + //now lets swap the next pointers |
| 66 | + Node *temp = curry->next; |
| 67 | + curry->next = currx->next; |
| 68 | + currx->next = temp; |
| 69 | +} |
| 70 | + |
| 71 | +void insert(Node* & head, int data) { |
| 72 | + if (head == nullptr) { |
| 73 | + head = new Node(data); |
| 74 | + return; |
| 75 | + } |
| 76 | + Node *temp = head; |
| 77 | + while(temp->next != nullptr) { |
| 78 | + temp = temp->next; |
| 79 | + } |
| 80 | + temp->next = new Node(data); |
| 81 | +} |
| 82 | + |
| 83 | +void printList(Node * head) { |
| 84 | + while (head) { |
| 85 | + std::cout << head->data << "-->"; |
| 86 | + head = head->next; |
| 87 | + } |
| 88 | + std::cout << "null" << std::endl; |
| 89 | +} |
| 90 | + |
| 91 | +int main() { |
| 92 | + Node *head = nullptr; |
| 93 | + insert(head, 10); |
| 94 | + insert(head, 15); |
| 95 | + insert(head, 12); |
| 96 | + insert(head, 13); |
| 97 | + insert(head, 20); |
| 98 | + insert(head, 14); |
| 99 | + printList(head); |
| 100 | + std::cout << "Replacing 12 with 20 and 20 with 12:\n"; |
| 101 | + swapSpecial(head, 12, 20); |
| 102 | + printList(head); |
| 103 | + |
| 104 | + return 0; |
| 105 | +} |
0 commit comments