Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct elem {
- int key;
- struct elem* next;
- } *start;
- void init() {
- start = NULL;
- }
- struct elem* swap(struct elem* p, struct elem* q) {
- struct elem* tmp = q->next;
- q->next = p;
- p->next = tmp;
- return q;
- }
- int sort(struct elem** start, int list_size) {
- struct elem** s;
- int i, j, swapped = 0;
- for (i = 0; i <= list_size; i++) {
- s = start;
- for (j = 0; j < list_size - i - 1; j++) {
- struct elem* p = *s;
- struct elem* q = p->next;
- if (p->key < q->key) {
- *s = swap(p, q);
- swapped = 1;
- }
- s = &(*s)->next;
- }
- if (swapped == 0)
- break;
- }
- return 0;
- }
- void add_b(int n) {
- elem* p = start;
- start = new elem;
- start->key = n;
- start->next = p;
- }
- void add_e(int n) {
- elem* p = start, * q = start;
- q = new elem;
- q->key = n;
- q->next = NULL;
- if (start) {
- while (p->next)
- p = p->next;
- p->next = q;
- }
- else
- start = q;
- }
- void output(struct elem* n) {
- while (n != NULL) {
- cout << n->key << " | ";
- n = n->next;
- }
- cout << endl;
- }
- int main() {
- init();
- int n, x, i = 0;
- cout << " > Enter key value for start element | ";
- cin >> n;
- add_b(n);
- i++;
- cout << " > Enter how many elements to add after start | ";
- cin >> x;
- for (int j = 0; j < x; j++) {
- cout << " > Enter key value for element " << i << " | ";
- cin >> n;
- add_e(n);
- i++;
- }
- cout << " > List before sort | ";
- output(start);
- sort(&start, i);
- cout << " > List after sort | ";
- output(start);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement