简体   繁体   中英

Node elements are not printing in Single Linked List Program

I have created here a C Program in TurboC++. This simple program goal is to just create a linked list, insert every element at the end of the list and then print the value of the nodes.(Edited The program is somewhat changed to make it easier for me to understand but still the problem of nodes not being priniting exists) The problem is, some of the node elements are not printing

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<ctype.h>
#include<conio.h>
struct node
{
  int data;
  struct node *link;
};
typedef struct node ND;
void main()
{
  ND *start,*current,*temp;
  start=NULL;
  do
  {
    temp=(ND*)malloc(sizeof(ND));
    printf("\n Enter Node Value");
    scanf(" %d",&temp->data);
    temp->link=NULL;
    if(start==NULL)
    {
      start=current=temp;
    }
    else
    {
      current->link=temp;
      current=temp;
    }
    fflush(stdin);
    printf("\nDo You Want TO Continue?(Y/N)");
  }while(toupper(getchar())!='N');
  current=start;
  printf("\nThe Elements OF Linked List ARE:");
  while(current!=NULL)
  {
    printf(" %d",current->data);
    current=current->link;
  }
}

You printing list from wrong element. You should start from head. like:

temp1 = head;
while(temp1!=NULL)
{
  printf(" %d",temp1->data);
  temp1=temp1->link;
}

By the way your head element will be always NULL. Here is correct way to add elements to list:

if (head == NULL)
{
    head = temp;
}
else
{
    temp1 = head;
    while (temp1->link != NULL)
    {
        temp1 = temp1->link;
    }
    temp1->link = temp;
}

The program is now working correctly i have made some changes to make this program easier to understand.Here's the code:

#include<stdio.h>
#include<conio.h> 
struct node
{
  int data;
  struct node *link;
};
typedef struct node ND;
void main()
{
  ND *head,*tail,*temp1;
  int n;
  char ch;
  printf("\nEnter Data?(y/n)\n");
  scanf(" %c",&ch);
  fflush(stdin);
  if(ch=='y' || ch=='Y')
  {
    tail=(ND*)malloc(sizeof(ND));
    printf("\n Enter Node Value");
    scanf(" %d",&n);
    tail->data=n;
    tail->link=NULL;
    head=tail;
    printf("\nDo You Want TO Continue?(Y/N)");
    scanf(" %c",&ch);
    fflush(stdin);
  }
  while(ch=='y' || ch=='Y')
  {
    printf("\n Enter Node Value");
    scanf(" %d",&n);
    tail->link=(ND*)malloc(sizeof(ND));
    tail->link->data=n;
    tail->link->link=NULL;
    tail=tail->link;
    printf("\nEnter More Data?(y/n)\n");
    scanf(" %c",&ch);
    fflush(stdin);
  }
  printf("\nElements Of Linked List Are:");
  temp1=head;
  while(temp1!=NULL)
  {
    printf(" %d",temp1->data);
    temp1=temp1->link;
  }
  printf("\n");
  fflush(stdout);
  getch();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM