/*
Summary: Linked list is an ordered set of data elements, each containing a link to its successor. This program is to create a linked list. After creating the linked list ,the length of linked list is calculated.
*/
#include<iostream>
#include<stdlib.h>
usingnamespace std;
#include <stdio.h>
#include <conio.h>
#define newnode (struct node*) malloc(sizeof(struct node))
struct node
{
int data;
struct node *next;
};
struct node *create_list();
int main()
{
struct node *f;
int len;
f = NULL;
clrscr();
f = create_list();
len = find_len(f);
printf("\n length = %d",len);
} // main
struct node *create_list()
{
struct node *f,*c,*p;
int tdata;
f = NULL;
printf("\n Enter data ( use 0 to exit ) : ");
scanf("%d",&tdata);
while( tdata != 0 )
{
c = newnode;
if( c == NULL)
{
printf("\n Insuf. mem. ");
exit(0);
}
c->data = tdata;
c->next = NULL;
if( f== NULL)
f = c;
else
p->next = c;
p = c;
printf("\n Enter data ( use 0 to exit ) : ");
scanf("%d",&tdata);
} //while
return(f);
} // create list
int find_len(struct node *f)
{
int len=0;
struct node *t;
if( f == NULL)
return(0);
t = f;
while( t != NULL )
{
len++;
t = t->next;
}
return(len);
}
/*
Input: Enter data ( use 0 to exit ) : 5
Enter data ( use 0 to exit ) : 15
Enter data ( use 0 to exit ) : 65
Enter data ( use 0 to exit ) : 2
Enter data ( use 0 to exit ) : 657
Enter data ( use 0 to exit ) : 3
Enter data ( use 0 to exit ) : 0
*/
Not sure how to fix it because 'find_len' is a function in the program
I have included the prototype :
int find_len(struct node *f);
The program now compiles okay, but I get the output:
length = 0
when I run the program. It is supposed to give the length of the list
So far I have not been able to duplicate your problem.
The only thing I can thing of is:
1 2
if( f == NULL)
return(0);
In the "find_len" function. When I entered three numbers it told me the length was 3.
The program ran here in the shell, but the output was strange. When I used VS2017 the input and output appeared to be correct.
C++ Shell
1
2
3
4
0
Enter data ( use 0 to exit ) :
Enter data ( use 0 to exit ) :
Enter data ( use 0 to exit ) :
Enter data ( use 0 to exit ) :
Enter data ( use 0 to exit ) :
length = 4
VS2017:
Enter data ( use 0 to exit ) : 1
Enter data ( use 0 to exit ) : 2
Enter data ( use 0 to exit ) : 3
Enter data ( use 0 to exit ) : 4
Enter data ( use 0 to exit ) : 0
length = 4
In "main" after "find_len" returns a value you could try this:
1 2 3 4
if (len > 0)
printf("\n length = %d", len);
else
printf("\n The list is empty");
It has been awhile since I have worked with C, but as I recall "calloc" and "malloc" both create their space on the heap. And once the memory had been created it needs to be freed when you are done using it. Otherwise you create a memory leak that could last after the program ends. Not sure how to do this right now, but the key word "free" comes to mind. I will have to look into that.