Implementation Of Linked List In C
Data Structures
C
LINKEDLIST
Linked List
A linked list is a linear data structure that includes a series of connected nodes. Here, each node stores the data and the address of the next node. For example,
Implementation Code
// CODE BY Anshul Saini
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
} *head = NULL, *p = NULL, *q , *temp;
int main(){
int num, i, data;
scanf("%d",&num);
for(i = 0; i < num; i++){
scanf("%d",&data);
q = (struct node*)malloc(sizeof(struct node));
q->data = data;
q->next = NULL;
if(p == NULL){
head = q; p = q;
}
else{
p->next = q;
p = q;
}
}
}
Print Linkedlist
temp = head;
while(temp != NULL){
printf("%d \n ",temp->data);
temp = temp->next;
}
Add Node At Beginning
scanf("%d",&data);
// create node
q = (struct node *)malloc(sizeof(struct node));
q->data = data;
q->next = head;
head = q;
Add Node At End
scanf("%d",&data);
// create new node
q = (struct node *)malloc(sizeof(struct node));
q->data = item;
q->next = NULL;
//Traverse List
while(temp->next != NULL){
temp =temp->next;
}
temp->next = q;
Delete Node From Begining
if(head != NULL){
temp = head;
head =head->next;
free(temp);
}
Delete Node From End
if(temp != NULL){
if(temp->next == NULL){
free(temp)
temp = NULL
}
else{
while(temp->next->next != NULL){
temp = temp->next;
}
free(temp->next);
temp->next = NULL;
}
}


Comments
Post a Comment
Please Enter Your View And Feedback About This Page