Hey all! I want to know if you can help me with something. I'm creating a singly linked list to be sorted. I can change it to a doubly linked list if need to. At the moment my Bubble Sort function sorts it well, but when I try and print it out again, there's double of one number, I remember seeing this kinda problem a year ago, but I don't remember how I fixed it.
Also, if you can suggest a better way to sort it, please do! Also incorporate on how I would go about writing the function as a linked list.
Thanks!
Here's the code:
Also, if you can suggest a better way to sort it, please do! Also incorporate on how I would go about writing the function as a linked list.
Thanks!
Here's the code:
Code:
#include <iostream>
using namespace std;
struct Node {
Node * next;
int data;
Node(Node * ptr = NULL, int _data = 0) : next(ptr), data(_data) {}
};
void insert(Node * &ptr, int d) {
ptr = new Node(ptr, d);
}
void display(Node * ptr) {
Node * curr = ptr;
cout << "{";
while(curr != 0) {
cout << curr->data;
if(curr->next != NULL)
cout << ", ";
curr = curr->next;
}
cout << "}" << endl;
}
void sortNodes(Node * ptr) {
Node * temp = ptr;
Node * curr;
for(bool didSwap = true; didSwap; ) {
didSwap = false;
for(curr = ptr; curr->next != NULL; curr = curr->next) {
if(curr->data > curr->next->data) {
temp->data = curr->data;
curr->data = curr->next->data;
curr->next->data = temp->data;
didSwap = true;
}
}
}
}
int main () {
int input;
Node * newNode;
cout << "Enter as many numbers as you want for the linked list. It will"
<< "automatically sort it. Press -1 to quit." << endl;
while(true) {
cin >> input;
if(input == -1)
break;
insert(newNode, input);
}
cout << "The list is: ";
display(newNode);
cout << endl;
cout << "The sorted list is: ";
sortNodes(newNode);
display(newNode->next);
cout << endl;
return 0;
}