problem linked list.

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;
}

https://www.prepaidgiftbalance.net/
Last edited on
Hi,

Let me introduce the concept of rubber duck debugging:

* Acquire a small rubber duck
* Explain to the duck out loud how the program works
* Realise where you went wrong, fix the code

It sounds silly, but I am serious.

Explain to us the algorithm for inserting values into the list, so they are sorted.

Also, what research have you done?
You first need to open the file

1
2
3
std::ifstream ifs("INPUT.txt");
if (!ifs)
    return (std::cout << "Cannot open file\n"), 1;


Then instead of using cin, you use ifs. Obviously the cout statement is also not needed. This is usually coded like:

 
for (int x{}; ifs >> x; Add(head, NULL, x));


However:
L8 - you don't need to use struct here

L13 Add() - why are you having p as an argument? Don't you just need head and the item to insert?

L23/24 v can be defined in the for rather than before.

L9/10 global variables are not good practice. These should be defined as part of main and passed as params to functions if required.

To insert in sorted order, you need to traverse the existing list to ascertain the position in which to insert the new item. You need to take care with a) empty list b) insertion at head c) insertion at end


Last edited on
Topic archived. No new replies allowed.