linked list problem

Hi guys, so here is my task :

Write a program that creates a simple linked list of N integers taken from the INPUT file. The last number entered is one. These numbers will be ordered (simultaneously with the reading) in descending order by operations on the elements and then will be displayed.

I wrote the program but i can't figure out how to take the input from the file and
order the numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
using namespace std;
struct nod
{
    int inf;
    nod* next;
};
typedef struct nod* List;
List head, p;
int x;

// Inserting a node
void Add(List& head, List p, int x)
{
    List q = new nod;
    q->inf = x;
    if (!p) { q->next = head; head = q; }
    else { q->next = p->next; p->next = q; }
}

void Display(List head)
{
    List v;
    for (v = head; v; v = v->next)
        cout << v->inf << " ";
    cout << endl;
}
int main()
{
    cout<<"Creating a list until 0 is met :"<<endl;
    cout << "Number :"; cin >> x;

    while (x) {
        Add(head, NULL, x);
        cout << "Number :"; cin >> x;
    }
    cout << endl << "Initially created list :" << endl;
    Display(head);  cout << endl;
    cout << "Moddified list :" << endl;
    Display(head); cout << endl;
    return 0;
}
Last edited on
Input from file stream is very similar to input from cin (which is also a stream) http://www.cplusplus.com/doc/tutorial/files/

Your Add() function should insert the new node into correct spot within the list.
In C++, there's no need to specifiy struct before referring to the name of a struct. L8 becomes:

 
typedef nod* List;


or as C++:

 
using List = nod*;


Add() needs to insert the element into the correct sorted position in the list. Iterate over the list until the position is found in which the new item should be inserted and then insert it there.

As you are using struct for the node, why not use a struct/class for the List when Add(0 etc would become class member functions?

Topic archived. No new replies allowed.