Skip to content

Create assignment_2 - #1

Open
omarahmed2205 wants to merge 1 commit into
dr-ahmed-said:masterfrom
omarahmed2205:patch-1
Open

Create assignment_2#1
omarahmed2205 wants to merge 1 commit into
dr-ahmed-said:masterfrom
omarahmed2205:patch-1

Conversation

@omarahmed2205

Copy link
Copy Markdown

#include
using namespace std;

struct Node {
int data;
Node* next;
Node* prev;
Node(int val) : data(val), next(nullptr), prev(nullptr) {}
};

Node* mergeLists(Node* L1, Node* L2) {
if (!L1) return L2;
if (!L2) return L1;

if (L1->data < L2->data) {
    L1->next = mergeLists(L1->next, L2);
    return L1;
} else {
    L2->next = mergeLists(L1, L2->next);
    return L2;
}

}

void swapAdjacentSingly(Node*& head, int key) {
if (!head || !head->next) return;
Node* prev = nullptr, curr = head;
while (curr && curr->next) {
if (curr->data == key) {
Node
temp = curr->next;
curr->next = temp->next;
temp->next = curr;
if (prev) prev->next = temp;
else head = temp;
break;
}
prev = curr;
curr = curr->next;
}
}

void swapAdjacentDoubly(Node*& head, int key) {
if (!head || !head->next) return;
Node* curr = head;
while (curr && curr->next) {
if (curr->data == key) {
Node* temp = curr->next;
if (temp->next) temp->next->prev = curr;
if (curr->prev) curr->prev->next = temp;
else head = temp;

        curr->next = temp->next;
        temp->prev = curr->prev;
        temp->next = curr;
        curr->prev = temp;
        break;
    }
    curr = curr->next;
}

}

void printList(Node* head) {
while (head) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}

int main() {
Node* L1 = new Node(1);
L1->next = new Node(3);
L1->next->next = new Node(5);

Node* L2 = new Node(2);
L2->next = new Node(4);
L2->next->next = new Node(6);

Node* merged = mergeLists(L1, L2);
printList(merged);

Node* singly = new Node(10);
singly->next = new Node(20);
singly->next->next = new Node(30);
swapAdjacentSingly(singly, 20);
printList(singly);

Node* doubly = new Node(10);
doubly->next = new Node(20);
doubly->next->prev = doubly;
doubly->next->next = new Node(30);
doubly->next->next->prev = doubly->next;
swapAdjacentDoubly(doubly, 20);
printList(doubly);

return 0;

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant