Linkedlist Creation and Traversal
Insertion of elements at end
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
int main(){
node *head = NULL;
int num,s;
printf("enter size of linked list:");
scanf("%d",&s);
for(int i = 0; i<s; i++){
node *n = (node*)malloc(sizeof(node));
if(n == NULL){
printf("Memory Allocation Failed\n");
return 1;
}
printf("enter value %d : ",i);
scanf("%d", &num);
n->data = num;
n->next = NULL;
if(head == NULL){
head = n;
}
else{
//variable need to be reach end so that we can add another node
node *p = head;
while(p->next != NULL){
p = p->next;
}
p->next = n;
}
}
node *ptr = head;
printf("\n\n\t**** Linked List ****\n\n");
while(ptr != NULL){
printf("%d->",ptr->data);
ptr = ptr->next;
}
printf("NULL");
//free memory
ptr = head;
while (ptr != NULL){
node *temp = ptr;
ptr = ptr->next;
free(temp);
}
}
Comments
Post a Comment