user3181231
user3181231

Reputation: 177

Not able to print the last element of list

I am trying to make a linked list but not able to print the last element or may be not able to add the last element. I am using the pointer to a pointer approach but keep getting confused with it. The list should show 6 but only reaches till 5.

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

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

 void push(struct node**,int);

 int main()
 {
 struct node* head=NULL;
 struct node* tail=NULL,*current=NULL;
 push(&head,1);
 current=head;

 tail=head;
 for(int i=2;i<7;i++)
    {
        push(&tail->next,i);

        tail=tail->next;

    }
   current=head;
  while(current->next!=NULL)
    {
        printf("\n%d--\n",current->data);
        current=current->next;

    } 
return 0;
}

void push(struct node** headref,int inp)

{
struct node* new=NULL;
new=malloc(sizeof(struct node));
new->data=inp;
new->next=*headref;
*headref=new;
}

Upvotes: 0

Views: 362

Answers (2)

Brightshine
Brightshine

Reputation: 965

The loop should be:

while(current!=NULL)
{
    printf("\n%d--\n",current->data);
    current=current->next;
}

And you can't use 'new' as a variable name, for it is reserved word

void push(struct node** headref,int inp)
{
    struct node* temp=NULL;
    temp=(node*)malloc(sizeof(struct node));
    temp->data=inp;
    temp->next=*headref;
    *headref=temp;
}

Upvotes: 1

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

You're stopping when the next element is NULL. Stop when the current one is NULL instead:

while (current) { … }

Upvotes: 2

Related Questions