See I created a program that accepts three values from the user to be arranged as a linked list(ascending order). After it asks a number, it displays the content of the list. The output is like this:
Enter number: 6
List value: 6
Enter number: 4
List value: 4 6
Enter value: 2
List value: 2 4 6
However, because of my limited knowledge about lists, I coded the program without using any kind of loop. My question is, is there any way I can shorten my code using a "for loop" perhaps? and Can I sort the numbers all at once without using conditional statement? Thanks!
#include<iostream>
using namespace std;
struct node{
int data; //data in node
node *next; //pointer to next node
};
int main()
{
node *p;
p = new node;
cout << "Give a number: ";
cin >> p->data;
p->next = NULL;
cout << "List contains: "<< p->data<<"";
node *q;
q = new node;
cout << "\nGive a number: ";
cin >> q->data;
p->next = NULL;
if(q->data > p->data){
cout << "List contains: " <<p->data<<" ";
cout << q->data;
p->next = q;}
else{
cout << "List contains: " <<q->data<<" ";
cout << p->data;
q->next = p;}
node *r;
r = new node;
cout << "\nGive a number: " ;
cin >> r->data;
r->next = NULL;
if(r->data > q->data && r->data > p->data){
cout << "List contains: ";
cout << ""<<p->data<<" "<<q->data<<" "<<r->data;
q->next = r;}
else if(r->data < q->data && r->data < p->data){
cout << "List contains: ";
cout << ""<<r->data<<" "<<p->data<<" "<<q->data;
r->next = p; p->next = q;}
else{
cout << "List contains: ";
cout << ""<<p->data<<" "<<r->data<<" "<<q->data;
p->next = r; r->next = q;}
system("pause>null");
return 0;
}