CHP 3
CHP 3
⚫ The first node is called head and the last node is called
tail
Linked List contd....
⚫ are dynamic data structures that grow and
shrink one element at a time
⚫ is a series of connected nodes
400 1200 memory
⚫ Head
Data Next Data Next Data Null
20 400 30 1200 40
Linked List contd....
⚫ Array allocates memory for all its elements in
one block(consecutive)
Eg int a[6];
200 202 204 206 208 210
0 1 2 3 4 6
node
Data next
C program
struct linked_list
{
int data;
struct linked_list *next; data next
}; new 20
NULL
void main
{
struct linked_list *new=NULL;
new=(struct linked_list*) malloc(sizeof(struct linked_list));
printf(“Enter data\n”);
scanf(“%d”, &new->data);
new->next=NULL;
}
typedef ...
struct linked_list
{
int data;
struct linked_list *next;
} typedef struct linked_list node;
void main
{
node *new=NULL;
new=(node *) malloc(sizeof(node));
printf(“Enter data\n”);
scanf(“%d”, &new->data);
new->next=NULL;
}
Creating 3 nodes
struct node
{
int data;
struct node * next;
};
void main() 2500
{ first 10 1500
struct node *first,*second,*third;
first=(struct node*)malloc(sizeof(node));
second=(struct node*)malloc(sizeof(node));
third=(struct node*)malloc(sizeof(node)); 1500
first->data=10;
first->next=second;
20 4000
second->data=20; second
second->next=third;
third->data=30; 4000
third->next=NULL;
} third 30 NULL
Printing Elements
struct node
{
int data;
struct node * next;
};
void main()
{ struct node *first,*second,*third,*head;
first=(struct node*)malloc(sizeof(node));
second=(struct node*)malloc(sizeof(node));
third=(struct node*)malloc(sizeof(node));
first->data=10;
first->next=second;
second->data=20;
second->next=third;
third->data=30;
third->next=NULL;
printf(“Data\n”);
head=first;
while(head!=NULL)
{ printf(“%d\n”,head->data);
head=head->next;
}
}
Linked list to store student rollno and name
struct node
{ roll name ptr
int roll;
char name[30];
struct 2bytes 30bytes 2bytes
};
void main()
{
struct node *s1,*s2,*s3;
s1=(struct node*)malloc(sizeof(node));
s2=(struct node*)malloc(sizeof(node)); s1 1 ana 1500
s3=(struct node*)malloc(sizeof(node));
s1->roll=1 ;
strcpy( s1->name,’ana’);
s1->next=s2;
s2->roll=2;
strcpy( s2->name,’sam’); s2 2 sam 4000
s2->next=s3;
s3>roll=3; 1500
strcpy(s3->name,’john’);
s3->next=NULL ;
} s3 30 john NULL
4000