Create a structure for node.see below code
struct node{
int data;
struct node *next;
};
int data;
struct node *next;
};
Create a head pointer that represents address of initial element in the list. When the list is empty who's value is NULL.
struct node *head=NULL;
Now, the following create() function is creates a list with required number of nodes.
void create(){
int ch;
struct node *newNode,*lastNode;
lastNode=(struct node*)malloc(sizeof(struct node*));
do{
newNode=(struct node*)malloc(sizeof(struct node*));
printf("Enter node value:\n");
scanf("%d",&newNode->data);
if(head==NULL)
head=newNode;
lastNode->next=newNode;
lastNode=newNode;
printf("To continue press 1 otherwise 0:\n");
scanf("%d",&ch);
}while(ch==1);
lastNode->next=NULL;
}
int ch;
struct node *newNode,*lastNode;
lastNode=(struct node*)malloc(sizeof(struct node*));
do{
newNode=(struct node*)malloc(sizeof(struct node*));
printf("Enter node value:\n");
scanf("%d",&newNode->data);
if(head==NULL)
head=newNode;
lastNode->next=newNode;
lastNode=newNode;
printf("To continue press 1 otherwise 0:\n");
scanf("%d",&ch);
}while(ch==1);
lastNode->next=NULL;
}
Finally, display list with traverse() function.
void traverse(){
struct node *ptr;
if(head==NULL){
printf("List is empty.\n");
}else{
ptr=head;
while(ptr!=NULL){
printf("%d->",ptr->data);
ptr=ptr->next;
}
printf("NULL");
}
}
struct node *ptr;
if(head==NULL){
printf("List is empty.\n");
}else{
ptr=head;
while(ptr!=NULL){
printf("%d->",ptr->data);
ptr=ptr->next;
}
printf("NULL");
}
}
Click on the below button for implementation of Singly Linked List with it's operations.
Related Programs
- Create Singly Linked List with N number of nodes and display.
- Perform insertion operation on Singly Linked List.
- Perform deletion operation on Singly Linked List.
- Reverse of Singly Linked List.
- Move last node of Singly Linked List to first.
- Swap first and last nodes in a Singly Linked List.
- Find the length of Singly Linked List.
- Find middle node of Singly Linked List