Created
September 21, 2021 22:23
-
-
Save manucabral/9f6fd959dc91284f8768bc96ab0eea83 to your computer and use it in GitHub Desktop.
sorting a single linked list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
struct Node | |
{ | |
int num; | |
Node *next; | |
}; | |
Node *last_node(Node *node) | |
{ | |
while (node && node->next) | |
node = node->next; | |
return node; | |
} | |
Node *next(Node *node) | |
{ | |
return node ? node->next : NULL; | |
} | |
int length(Node *node) | |
{ | |
int c = 0; | |
while (node) | |
{ | |
c++; | |
node = next(node); | |
} | |
return c; | |
} | |
void push(Node *&root, int value) | |
{ | |
Node *new_node = new Node(); | |
Node *last = NULL; | |
new_node->num = value; | |
new_node->next = NULL; | |
if (root) | |
{ | |
last = last_node(root); | |
last->next = new_node; | |
} | |
else | |
root = new_node; | |
} | |
Node *swap(Node *a, Node *b) | |
{ | |
Node *tmp = b->next; | |
b->next = a; | |
a->next = tmp; | |
return b; | |
} | |
void sort(Node *&node) | |
{ | |
for (Node *i = node; i->next; i = i->next) | |
for (Node *j = i->next; j; j = j->next) | |
if (i->num > j->num) | |
swap(i->num, j->num); | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
Node *alpha = NULL; | |
push(alpha, 5); | |
push(alpha, 4); | |
push(alpha, 104); | |
push(alpha, 8); | |
sort(alpha); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment