trying to implement bubble sort using linked list but its not working. can anyone identify the problem in my code. i think in class singlylinkedist there is a function called bubblesort in which for loop is not working, for completely sorting the linked list. It only sorts the list once but not sorts it till the size of the linked list.
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
Node()
{
data = 0;
next = NULL;
}
Node(int d)
{
data = d;
}
};
class singlylinkedlist{
public:
Node *head,*tail;
singlylinkedlist()
{
head = NULL;
tail = NULL;
}
void appendNode(Node *temp)
{
if (head == NULL)
{
head = temp;
tail = temp;
cout << "Node Appended" << endl;
}
else
{
tail->next = temp;
tail = tail->next;
cout << "Node Appended" << endl;
}
}
void prependNode(Node *temp)
{
temp->next = head;
head = temp;
cout<< "Node Prepended" << endl;
}
int getdata(int pos)
{
Node *curr = new Node;
curr = head;
for(int i=1;i<pos;i++)
{
curr = curr->next;
}
return curr->data;
}
void printList()
{
if (head == NULL)
{
cout << "No Nodes in Singly Linked List";
}
else
{
cout << endl << "Singly Linked List Values : ";
Node *temp = head;
while (temp != NULL)
{
cout << "--> "<<temp -> data;
temp = temp -> next;
}
cout<<"\n";
}
}
int ListSize()
{
int count=0;
if (head == NULL)
{
cout << "No Nodes in Singly Linked List";
}
else
{
Node *temp = head;
while (temp != NULL)
{
temp = temp -> next;
count = count+1;
}
}
return count;
}
void bubblesort(Node *temp)
{
temp= head;
Node *ptr;
Node *prev = NULL;
for(int j=0;j<ListSize();j++)
{
while(temp!=NULL && temp->next!=NULL){
if(temp->data > temp->next->data){
if(prev == NULL){
ptr = temp->next;
temp->next = ptr->next;
ptr->next = temp;
head = prev = ptr;
}
else{
ptr = temp->next;
prev->next = ptr;
temp->next = ptr->next;
ptr->next = temp;
prev = ptr;
}
}
else{
ptr = temp->next;
prev = temp;
temp = ptr;
}
}
}
}
};
int main()
{
singlylinkedlist s;
int option;
int data1;
int pos;
do{
cout << "\nWhat operation do you want to perform? Select Option number. Enter 0 to exit." << endl;
cout << "1. appendNode()" << endl;
cout << "2. prependNode()" << endl;
cout << "3. getdata()" << endl;
cout << "6. printList()" << endl;
cout << "7. bubblesort()" << endl;
cin>>option;
Node *temp = new Node;
switch (option) {
case 0:
break;
case 1:
cout << "Append Node Operation \nEnter data of the Node to be Appended" << endl;
cin >> data1;
temp->data = data1;
temp->next = NULL;
s.appendNode(temp);
break;
case 2:
cout<<"Prepend Node Operation \nEnter data of the Node to be Prepended" << endl;
cin>>data1;
temp->data = data1;
temp->next = NULL;
s.prependNode(temp);
break;
case 3:
cout<<"enter position to get data"<<endl;
cin>>pos;
cout<<"DATA AT GIVEN INDEX IS " << s.getdata(pos);
break;
case 6:
s.printList();
break;
case 7:
s.bubblesort(temp);
s.printList();
break;
}
}while (option != 0);
}
getdatais completely pointless and leaks memory in literally two short lines. Just saying.ints in an array?