0

This is how my program is but it doesn't print the full list only node's data which entered last.I couldn't understand what is the problem in linking or not :

basic Structure of node

    struct node
    {
        int data;
        struct node *link;
    };

defining header as start of link list :

    struct node *header;

Functions for Insert and print :

    void insertFront_sl();
    void print_sl();

The main function :

    void main()
    {
    clrscr();
    header=(struct node *)malloc(sizeof(struct node));
    header->link=NULL;
    header->data=NULL;
    insertFront_sl();
    insertFront_sl();
    insertFront_sl();
    insertFront_sl();
    print_sl();
    getch();
    }


    void insertFront_sl(){
    struct node *temp;
    int x;
    temp=(struct node *)malloc(sizeof(struct node));
    if(temp==NULL)
    {
    printf("\nMeM0rY Insufficient ..");
    }
    else
    {
        printf("\nGot New Node \nNow Insert Data Into Node : ");
    scanf("%d",&x);


    temp->data=x;
    header->link=temp;


    }

    }

    void print_sl(){
    struct node *ptr;
    ptr=header;
    while(ptr->link !=NULL)
    {
        ptr=ptr->link;
        printf("%d\t",ptr->data);
    }


    }
Hiren
  • 613
  • 1
  • 8
  • 25

4 Answers4

2

header->link=temp; discards the tail of the list. It should be:

temp->link = header;
header = temp;
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
1

Each time you create a new node you are losing the reference to nodes you created previously. After you add the new node:

header->link=temp;

you need to set the head of the list to the new node:

header = temp;

You should also keep a node as a reference to the base of the list (the first node), and use this base as your starting point for printing the list.

Paddyd
  • 1,870
  • 16
  • 26
0

This is how my program is but it doesn't print the full list only node's data which entered last.

header->link=temp;

The problem is that you are always adding the new element to the current node itself. You are loosing the reference to the node you added earlier and causing a memory leak.

Mahesh
  • 34,573
  • 20
  • 89
  • 115
0

The problem is in the linking. Each time you insert you are making the pointer in the header node point to your newest link, which overwrites the old pointer value (which pointed to the previous new link). Instead, you need to make sure that you set temp->link to the previous "new" link before making the header refer to temp.

tuckermi
  • 839
  • 6
  • 17