Linked List Linked List Linked List Linked List
Linked List Linked List Linked List Linked List
Linked List Linked List Linked List Linked List
List
Linked List
Structure 2
data
Structure 3
data
3
Contd.
struct node
{
int data;
struct node *next;
}
data
next
node
b
1
NULL
data next
c
2
NULL
data next
NULL
data next
b
1
data next
c
2
data next
NULL
data next
b
1
data next
c
2
data next
NULL
data next
2
3
Linked Lists
next
data
node
NULL
Contd.
head
NULL
10
Contd.
struct node_name
{
Data items in each
type member1;
element of the list
type member2;
12
Contd.
n1
n2
n3
13
n1.next
n2.next
n3.next
=
=
=
&n2 ;
&n3 ;
NULL ;
15
15
Alternative Way
16
15
18
struct node {
int data ;
struct node * next ;
};
struct node *p, *q;
12
7
NULL
data
int
next
node *
17
Adding 15
and 18 only
struct node {
int data ;
struct node * next ;
};
struct node *p, *q;
15
q = (str
(struct node *) malloc(sizeof(struct node));
q->data=18; q->next = NULL;
15
18
NULL
q
p->next = q;
15
18
q
NULL
18
Output
Data = 15
Data = 18
We could have
done anything else
other than printing
as we traverse each
element, like
searching for
example. Just like
traversing an array.
19
Contd.
Solution:
Remember
20
Important to remember
24
at front of list
Insert at end of list
Insert in sorted order
Insertion in a list
To
Correct
in sorted order
27
Takes the
head pointer
and the value
to be inserted
(NULL if list is
empty)
Inserts the
value as the
first element of
the list
Returns the
new head
pointer value
28
Contd.
18
15
18
15
18
r
29
Output
List = {10, }
List = {11, 10, }
List = {12, 11, 10, }
30
Takes the
head pointer
and the value
to be inserted
(NULL if list is
empty)
Inserts the
value as the
last element of
the list
Returns the
new head
pointer value
Insert at end
struct node *insert_end(struct node *r,
int value)
{ struct node *p,*q;
p = (struct node *) malloc(sizeof(struct node));
p->data
>data = value;
p ->next
>next = NULL;
if (r==NULL
LL) return p; /* list passed is empty */
q=r;
while (q->next!=NULL)
>next!=NULL)
q=q->next;
>next; /* find the last element */
q->next =p;
return r;
}
31
Contd.
11
NULL
11
15
NULL
NULL
11
15
q
NULL
32
Output
List = {10, }
List = {10, 11, }
List = {10, 11, 12, }
33
prev
new
ptr
8
12
34
int main()
{
struct node *start;
int i,n,value;
start = NULL;
scanf("%d",&n);
for(i=0; i<n; i++) {
printf("Give Data: " );
scanf("%d",&value);
start = insert_asc(start, value);
}
display(start);
return 0;
}
35
Find
36
Example of Deletion
first
prev
ptr
12
Deleting an element
struct node * delete(struct node * r, int value)
{ struct node *p, *q;
p =r;
11
q = p;
q
while(p!=NULL) {
if (p->data == value){
if (p==r) r = p->next;
else q->next = p->next;
p->next = NULL;
11
free(p);
q
return r;
}
else { q = p;
p = p->next;
11
}
q
}
return r;
}
delete(r,4)
15
15
15
4
p NULL
38
Exercises
Print a list backwards (try a recursive print)
Count the number of elements in a list
(both using and not using recursion)
Concatenate two lists
Reverse a list
39