How does the functions for creating nodes can be used to create a linear linked list with n nodes? The linear linked list that will be created will be assigned values from 1 to n, right? The newly created linear linked list is returned by the function create linear() below.

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

struct node *createlinear(int n)
{
int i;
struct node *ptr, *tail, *list;
/*create the nodes*/
list=NULL;
}
for(i=1;i<=n;i++)
{
ptr=(struct node*)malloc(sizeof(struct node));
ptr=>value=i;
if(i>1)
{
tail->next=ptr;
ptr->next=NULL;
tail=ptr;
}
else{
list=ptr;
list->next=NULL;
tail=list;
}
}
return(list);
}

In the code, the pointer variable tail is used to point to the last node inserted in the linked list. A new node (pointed by ptr) is always inserted after the node pointed to by tail (this is clear from tail->next=ptr;).

NULL and malloc are undeclared. How is that? And where will I put int main()?

i think there is alot of errors please recheck the code then try to use the null and malloc

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

struct list
{
int data;
struct list *ptr;
};

main()
{
struct list *clist;
struct list *top;
struct list *tmpptr;
int i;

clist=(struct list *)malloc(sizeof(struct list *));
top=clist;
for(i=1;i<5;i++)
{
clist->data = i;
tmpptr=(struct list *)malloc(sizeof(struct list *));
clist->ptr=tmpptr;
clist=tmpptr;
}
for(clist=top;clist->ptr;clist=clist->ptr);
printf("%d\n", clist->data);
getchar();

}

So i rechecked the codes.. There is no error now, but it doesn't print my desired output. What is wrong with my codes?

there are 4 issues
1: you allocate the size of pointer not the size of strcu so change

malloc(sizeof(struct list *))

to

malloc(sizeof(struct list))

2: you always allocate one extra node at end so you need to remove it
3:and when create new node make its ptr = NULL
4: after the for loop of printing you added ; which make the loop empty and print the null

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.