0

The below code is supposed to add a node at the front of a linked list and print the current elements. But running this code gives me run time error and the program terminates. When asking for how many numbers and i typed a number and then it shows "main.cpp has stopped working". What might be wrong ?

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

struct Node
{

    int data;
    Node* next;
};
struct Node* head;
using namespace std;
void Insert(int x)
{
        Node* temp=new Node();
        temp->data=x;
        temp->next=head;
        head=temp;


}

void Print()
{
    Node* temp1=head;
    while(temp1!=NULL)
    {
        printf("%d\n",temp1->data);
        temp1=temp1->next;

    }
    printf("\n");
}

int main()
{
    head=NULL;
    printf("how many numbers?\n");
    int n,i,x;
    scanf("%d",n);
    for(i=0;i<n;i++)
    {
        printf("Enter the number: \n");
        scanf("%d",x);
        Insert(x);
        Print();
    }
    return 0;

}

7
  • 1
    Questions seeking debugging help (‘why isn't this code working?’) must include the desired behaviour, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. Commented Jan 1, 2017 at 21:06
  • 1
    scanf("%d", &n); Note the ampersand. Commented Jan 1, 2017 at 21:09
  • 2
    On a sidenote: You should learn to clean up - delete the memory you allocated when done. Commented Jan 1, 2017 at 21:11
  • 1
    Are you sure that this is C++? Commented Jan 1, 2017 at 21:11
  • 1
    This is not C++ - Use this to do the business. Also look into ifrsteam, Commented Jan 1, 2017 at 21:15

1 Answer 1

2

It's not even a linked list problem:

int n,i,x;
scanf("%d",n);

should be

int n,i,x;
scanf("%d",&n);

(there's another occurrence of that below)

because scanning integers need their address, as opposed to strings.

Sign up to request clarification or add additional context in comments.

1 Comment

BTW forget what I said about your linked list (now edited out), insertion looks okay. Trying to be a smartass needs more testing :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.