0

sorting the linear linked list by using structures in c++ and display - this is main objective

like linked list given as - 50 20 43 80 73 into sorted format - 20 43 50 73 80 Please check the problem in sorting it is not done perfectly . So , my codes in C++ is given below #include<iostream> #include<cstdlib> using namespace std; struct node { int data; struct node *next; }; struct node * head; struct node *create(int data) { struct node *ptr = new node; ptr->data = data; ptr->next = NULL; return (ptr); } void insert(int data) { struct node *ptr = head,*temp = create(data); if(head==NULL) head = temp; else { while(ptr->next!=NULL) ptr = ptr->next; ptr->next = temp; } } void sort() { struct node *ptr = head; int temp = 0; while(ptr->next!=NULL) { if(ptr->data>ptr->next->data) { temp = ptr->data; ptr->data = ptr->next->data; ptr->next->data = temp; ptr = head; } ptr = ptr->next; ptr = head; } cout<<endl; } void display() { struct node *ptr = head; cout<<"\n The linked list are as follows : "; while(ptr!=NULL) { cout<<ptr->data<<" "; ptr = ptr->next; } cout<<endl<<endl; } int main() { insert(20); insert(25); insert(50); insert(40); insert(3); display(); sort(); display(); } //Thank you coding buddy

7th Dec 2021, 4:20 PM
Praween Gupta
Praween Gupta - avatar
4 odpowiedzi
+ 2
I was thinking 1. Iterate the list to collect all nodes' data into an array 2. Sort the array 3. Iterate the list again, this time overwrite each node's data by respective data from the array.
13th Dec 2021, 5:12 AM
Ipang
+ 2
Okay bro 👌 Teacher knows it all ...
13th Dec 2021, 5:47 AM
Ipang
+ 2
Haha
13th Dec 2021, 5:50 AM
Praween Gupta
Praween Gupta - avatar
+ 1
Yeah, I think too about all the values goes to array and sort it but my teacher says a big NO, because it is not good code because it takes double data and time hence increasing time complexity and space consuming. Well thanks bro for opinion and also i make it but i have to use double loop and well it takes 3 days and all but atleast it is done.
13th Dec 2021, 5:28 AM
Praween Gupta
Praween Gupta - avatar