#include <iostream>
using namespace std;
struct Linknode {
int data;
struct Linknode* next;
};
void print(Linknode* header) {
Linknode* pcurrent = header->next;
while (pcurrent != NULL) {
cout << pcurrent->data << " ";
pcurrent = pcurrent->next;
}
cout << endl;
}
int check(int n, Linknode* header) {
Linknode* pcurrent = header->next;
while (pcurrent != NULL) {
if (pcurrent->data == n) {
cout << "Duplicate entry, please re-enter." << endl;
return 1;
}
pcurrent = pcurrent->next;
}
return 0;
}
void exchange(int x, int y, Linknode* header) {
if (x == y) return;
Linknode *px_prev = NULL, *px = header->next;
Linknode *py_prev = NULL, *py = header->next;
// Find nodes and their previous nodes
for (int i = 1; i < x && px != NULL; i++) {
px_prev = px;
px = px->next;
}
for (int i = 1; i < y && py != NULL; i++) {
py_prev = py;
py = py->next;
}
if (px == NULL || py == NULL) return;
// Swap nodes
if (px_prev != NULL) px_prev->next = py;
else header->next = py;
if (py_prev != NULL) py_prev->next = px;
else header->next = px;
Linknode* temp = px->next;
px->next = py->next;
py->next = temp;
}
Linknode* create() {
Linknode* header = new Linknode;
header->data = -1;
header->next = NULL;
Linknode* tail = header;
int val;
while (true) {
cin >> val;
if (val == 0) break;
if (check(val, header)) continue;
Linknode* newnode = new Linknode;
newnode->data = val;
newnode->next = NULL;
tail->next = newnode;
tail = newnode;
print(header);
}
return header;
}
void sort(Linknode* header) {
if (header == NULL || header->next == NULL) return;
Linknode *i, *j;
for (i = header->next; i != NULL; i = i->next) {
for (j = i->next; j != NULL; j = j->next) {
if (i->data > j->data) {
exchange(i->data, j->data, header);
}
}
}
}
int main() {
char command;
do {
Linknode* header = create();
sort(header);
print(header);
cout << "Enter '@' to exit or any other key to continue: ";
cin >> command;
} while (command != '@');
return 0;
}