Skip to content

Instantly share code, notes, and snippets.

@piusayowale
Created January 22, 2022 15:44
Show Gist options
  • Save piusayowale/23e77b62e38171aa6e9de8b6fec69dcd to your computer and use it in GitHub Desktop.
Save piusayowale/23e77b62e38171aa6e9de8b6fec69dcd to your computer and use it in GitHub Desktop.
Linked list with swap function
struct Node {
int value;
Node* next;
};
Node* insert(Node*& list, int value) {
Node* temp = nullptr;
Node* ptr = list;
if (ptr == nullptr) {
temp = new Node;
temp->value = value;
temp->next = nullptr;
list = temp;
return list;
}
while (ptr->next != nullptr)
{
ptr = ptr->next;
}
temp = new Node;
temp->value = value;
temp->next = NULL;
ptr->next = temp;
return list;
}
void print(Node* list) {
while (list != nullptr)
{
std::cout << list->value << " ";
list = list->next;
}
std::cout << "\n";
}
bool search(Node*& list, int value, Node *& ptr_out) {
ptr_out = list;
if (list == nullptr) {
return false;
}
while (ptr_out != nullptr && ptr_out->value != value)
{
ptr_out = ptr_out->next;
}
if (ptr_out == nullptr) {
return false;
}
return true;
}
void swap(Node** first, Node** second)
{
Node* tmp = *first;
*first = *second;
*second = tmp;
}
Node* swap(Node*& list, int a, int b) {
Node** pos_a = nullptr;
Node** pos_b = nullptr;
Node** ptr = &list;
Node** ptr2 = &list;
while ((*(ptr)) != nullptr)
{
if ((*(ptr))->value == a) {
pos_a = ptr;
break;
}
ptr = &(*(ptr))->next;
}
while ((*(ptr2)) != nullptr)
{
if ((*(ptr2))->value == b) {
pos_b = ptr2;
break;
}
ptr2 = &(*(ptr2))->next;
}
if (pos_a == nullptr || pos_b == nullptr) {
return nullptr;
}
swap(pos_a, pos_b);
swap(&(*pos_a)->next, &(*pos_b)->next);
return list;
}
int main() {
Node* list = nullptr;
list = insert(list, 6);
list = insert(list, 8);
list = insert(list, 2);
list = insert(list, 1);
list = insert(list, 9);
list = insert(list, 7);
list = insert(list, 0);
print(list);
list = swap(list, 1, 0);
print(list);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment