SlideShare a Scribd company logo
1 of 83
PDS Class Test 2
โ€ข Date: October 27, 2016
โ€ข Time: 7pm to 8pm
โ€ข Marks: 20 (Weightage 50% i.e. max. 10 to the total score)
Room Sections No of students
V1 Section 8 (All)
Section 9
(AE,AG,BT,CE, CH,CS,CY,EC,EE,EX)
101
49
V2 Section 9 (Rest, if not allotted in V1)
Section 10 (All)
50
98
V3 Section 11 (All) 98
V4 Section 12 (All) 94
F116 Section 13 (All) 95
F142 Section 14 (All) 96
Autumn 2016 Programming and Data Structure 1
Linked List
Spring 2012 Programming and Data Structure 2
Introduction
โ€ข A linked list is a data structure which can change
during execution.
โ€“ Successive elements are connected by pointers.
โ€“ Last element points to NULL.
โ€“ It can grow or shrink in size during execution of a
program.
โ€“ It can be made just as long as required.
โ€“ It does not waste memory space.
Spring 2012 Programming and Data Structure 3
A B C
head
โ€ข Keeping track of a linked list:
โ€“ Must know the pointer to the first element of the
list (called start, head, etc.).
โ€ข Linked lists provide flexibility in allowing the
items to be rearranged efficiently.
โ€“ Insert an element.
โ€“ Delete an element.
Spring 2012 Programming and Data Structure 4
Illustration: Insertion
Spring 2012 Programming and Data Structure 5
A
A
Item to be
inserted
X
X
A B C
B C
curr
tmp
Pseudo-code for insertion
Spring 2012 Programming and Data Structure 6
typedef struct nd {
struct item data;
struct nd * next;
} node;
void insert(node *curr)
{
node * tmp;
tmp=(node *) malloc(sizeof(node));
tmp->next=curr->next;
curr->next=tmp;
}
Illustration: Deletion
Spring 2012 Programming and Data Structure 7
A B
A B C
C
Item to be deleted
curr
tmp
Pseudo-code for deletion
Spring 2012 Programming and Data Structure 8
typedef struct nd {
struct item data;
struct nd * next;
} node;
void delete(node *curr)
{
node * tmp;
tmp=curr->next;
curr->next=tmp->next;
free(tmp);
}
In essence ...
โ€ข For insertion:
โ€“ A record is created holding the new item.
โ€“ The next pointer of the new record is set to link it to
the item which is to follow it in the list.
โ€“ The next pointer of the item which is to precede it
must be modified to point to the new item.
โ€ข For deletion:
โ€“ The next pointer of the item immediately preceding
the one to be deleted is altered, and made to point
to the item following the deleted item.
Spring 2012 Programming and Data Structure 9
Array versus Linked Lists
โ€ข Arrays are suitable for:
โ€“ Inserting/deleting an element at the end.
โ€“ Randomly accessing any element.
โ€“ Searching the list for a particular value.
โ€ข Linked lists are suitable for:
โ€“ Inserting an element.
โ€“ Deleting an element.
โ€“ Applications where sequential access is required.
โ€“ In situations where the number of elements cannot
be predicted beforehand.
Spring 2012 Programming and Data Structure 10
Types of Lists
โ€ข Depending on the way in which the links are
used to maintain adjacency, several different
types of linked lists are possible.
โ€“ Linear singly-linked list (or simply linear list)
โ€ข One we have discussed so far.
Spring 2012 Programming and Data Structure 11
A B C
head
โ€“ Circular linked list
โ€ข The pointer from the last element in the list points back
to the first element.
Spring 2012 Programming and Data Structure 12
A B C
head
โ€“ Doubly linked list
โ€ข Pointers exist between adjacent nodes in both
directions.
โ€ข The list can be traversed either forward or backward.
โ€ข Usually two pointers are maintained to keep track of
the list, head and tail.
Spring 2012 Programming and Data Structure 13
A B C
head tail
Basic Operations on a List
โ€ข Creating a list
โ€ข Traversing the list
โ€ข Inserting an item in the list
โ€ข Deleting an item from the list
โ€ข Concatenating two lists into one
Spring 2012 Programming and Data Structure 14
List is an Abstract Data Type
โ€ข What is an abstract data type?
โ€“ It is a data type defined by the user.
โ€“ Typically more complex than simple data types like
int, float, etc.
โ€ข Why abstract?
โ€“ Because details of the implementation are hidden.
โ€“ When you do some operation on the list, say insert
an element, you just call a function.
โ€“ Details of how the list is implemented or how the
insert function is written is no longer required.
Spring 2012 Programming and Data Structure 15
Conceptual Idea
Spring 2012 Programming and Data Structure 16
List
implementation
and the
related functions
Insert
Delete
Traverse
Example: Working with linked list
โ€ข Consider the structure of a node as follows:
struct stud {
int roll;
char name[25];
int age;
struct stud *next;
};
/* A user-defined data type called โ€œnodeโ€ */
typedef struct stud node;
node *head;
Spring 2012 Programming and Data Structure 17
Creating a List
Spring 2012 Programming and Data Structure 18
How to begin?
โ€ข To start with, we have to create a node (the
first node), and make head point to it.
head = (node *)
malloc(sizeof(node));
Spring 2012 Programming and Data Structure 19
head
age
name
roll
next
Contd.
โ€ข If there are n number of nodes in the initial
linked list:
โ€“ Allocate n records, one by one.
โ€“ Read in the fields of the records.
โ€“ Modify the links of the records so that the chain is
formed.
Spring 2012 Programming and Data Structure 20
A B C
head
node *create_list()
{
int k, n;
node *p, *head;
printf ("n How many elements to enter?");
scanf ("%d", &n);
for (k=0; k<n; k++)
{
if (k == 0) {
head = (node *) malloc(sizeof(node));
p = head;
}
else {
p->next = (node *) malloc(sizeof(node));
p = p->next;
}
scanf ("%d %s %d", &p->roll, p->name, &p->age);
}
p->next = NULL;
return (head);
}
Spring 2012 Programming and Data Structure 21
โ€ข To be called from main() function as:
node *head;
โ€ฆโ€ฆโ€ฆ
head = create_list();
Spring 2012 Programming and Data Structure 22
Traversing the List
Spring 2012 Programming and Data Structure 23
What is to be done?
โ€ข Once the linked list has been constructed and
head points to the first node of the list,
โ€“ Follow the pointers.
โ€“ Display the contents of the nodes as they are
traversed.
โ€“ Stop when the next pointer points to NULL.
Spring 2012 Programming and Data Structure 24
void display (node *head)
{
int count = 1;
node *p;
p = head;
while (p != NULL)
{
printf ("nNode %d: %d %s %d", count,
p->roll, p->name, p->age);
count++;
p = p->next;
}
printf ("n");
}
Spring 2012 Programming and Data Structure 25
โ€ข To be called from main() function as:
node *head;
โ€ฆโ€ฆโ€ฆ
display (head);
Spring 2012 Programming and Data Structure 26
Inserting a Node in a List
Spring 2012 Programming and Data Structure 27
How to do?
โ€ข The problem is to insert a node before a
specified node.
โ€“ Specified means some value is given for the node
(called key).
โ€“ In this example, we consider it to be roll.
โ€ข Convention followed:
โ€“ If the value of roll is given as negative, the node
will be inserted at the end of the list.
Spring 2012 Programming and Data Structure 28
Contd.
โ€ข When a node is added at the beginning,
โ€“ Only one next pointer needs to be modified.
โ€ข head is made to point to the new node.
โ€ข New node points to the previously first element.
โ€ข When a node is added at the end,
โ€“ Two next pointers need to be modified.
โ€ข Last node now points to the new node.
โ€ข New node points to NULL.
โ€ข When a node is added in the middle,
โ€“ Two next pointers need to be modified.
โ€ข Previous node now points to the new node.
โ€ข New node points to the next node.
Spring 2012 Programming and Data Structure 29
Spring 2012 Programming and Data Structure 30
void insert (node **head)
{
int k = 0, rno;
node *p, *q, *new;
new = (node *) malloc(sizeof(node));
printf ("nData to be inserted: ");
scanf ("%d %s %d", &new->roll, new->name, &new->age);
printf ("nInsert before roll (-ve for end):");
scanf ("%d", &rno);
p = *head;
if (p->roll == rno) /* At the beginning */
{
new->next = p;
*head = new;
}
Spring 2012 Programming and Data Structure 31
else
{
while ((p != NULL) && (p->roll != rno))
{
q = p;
p = p->next;
}
if (p == NULL) /* At the end */
{
q->next = new;
new->next = NULL;
}
else if (p->roll == rno)
/* In the middle */
{
q->next = new;
new->next = p;
}
}
}
The pointers
q and p
always point
to consecutive
nodes.
โ€ข To be called from main() function as:
node *head;
โ€ฆโ€ฆโ€ฆ
insert (&head);
Spring 2012 Programming and Data Structure 32
Deleting a node from the list
Spring 2012 Programming and Data Structure 33
What is to be done?
โ€ข Here also we are required to delete a specified
node.
โ€“ Say, the node whose roll field is given.
โ€ข Here also three conditions arise:
โ€“ Deleting the first node.
โ€“ Deleting the last node.
โ€“ Deleting an intermediate node.
Spring 2012 Programming and Data Structure 34
Spring 2012 Programming and Data Structure 35
void delete (node **head)
{
int rno;
node *p, *q;
printf ("nDelete for roll :");
scanf ("%d", &rno);
p = *head;
if (p->roll == rno)
/* Delete the first element */
{
*head = p->next;
free (p);
}
Spring 2012 Programming and Data Structure 36
else
{
while ((p != NULL) && (p->roll != rno))
{
q = p;
p = p->next;
}
if (p == NULL) /* Element not found */
printf ("nNo match :: deletion failed");
else if (p->roll == rno)
/* Delete any other element */
{
q->next = p->next;
free (p);
}
}
}
Few Exercises to Try Out
โ€ข Write a function to:
โ€“ Concatenate two given list into one big list.
node *concatenate (node *head1, node *head2);
โ€“ Insert an element in a linked list in sorted order.
The function will be called for every element to
be inserted.
void insert_sorted (node **head, node *element);
โ€“ Always insert elements at one end, and delete
elements from the other end (first-in first-out
QUEUE).
void insert_q (node **head, node *element)
node *delete_q (node **head) /* Return the deleted node */
Spring 2012 Programming and Data Structure 37
A First-in First-out (FIFO) List
Spring 2012 Programming and Data Structure 38
Also called a QUEUE
In Out
A
C B
A
B
A Last-in First-out (LIFO) List
Spring 2012 Programming and Data Structure 39
In Out
A
B
C C
B
Also called a
STACK
Abstract Data Types
Spring 2012 Programming and Data Structure 40
Example 1 :: Complex numbers
struct cplx {
float re;
float im;
}
typedef struct cplx complex;
complex *add (complex a, complex b);
complex *sub (complex a, complex b);
complex *mul (complex a, complex b);
complex *div (complex a, complex b);
complex *read();
void print (complex a);
Spring 2012 Programming and Data Structure 41
Structure
definition
Function
prototypes
Spring 2012 Programming and Data Structure 42
Complex
Number
add
print
mul
sub
read
div
Example 2 :: Set manipulation
struct node {
int element;
struct node *next;
}
typedef struct node set;
set *union (set a, set b);
set *intersect (set a, set b);
set *minus (set a, set b);
void insert (set a, int x);
void delete (set a, int x);
int size (set a);
Spring 2012 Programming and Data Structure 43
Structure
definition
Function
prototypes
Spring 2012 Programming and Data Structure 44
Set
union
size
minus
intersect
delete
insert
Example 3 :: Last-In-First-Out STACK
Assume:: stack contains integer elements
void push (stack *s, int element);
/* Insert an element in the stack */
int pop (stack *s);
/* Remove and return the top element */
void create (stack *s);
/* Create a new stack */
int isempty (stack *s);
/* Check if stack is empty */
int isfull (stack *s);
/* Check if stack is full */
Spring 2012 Programming and Data Structure 45
Spring 2012 Programming and Data Structure 46
STACK
push
create
pop
isfull
isempty
Contd.
โ€ข We shall look into two different ways of
implementing stack:
โ€“ Using arrays
โ€“ Using linked list
Spring 2012 Programming and Data Structure 47
Example 4 :: First-In-First-Out
QUEUE
Assume:: queue contains integer elements
void enqueue (queue *q, int element);
/* Insert an element in the queue */
int dequeue (queue *q);
/* Remove an element from the queue */
queue *create();
/* Create a new queue */
int isempty (queue *q);
/* Check if queue is empty */
int size (queue *q);
/* Return the no. of elements in queue */
Spring 2012 Programming and Data Structure 48
Spring 2012 Programming and Data Structure 49
QUEUE
enqueue
create
dequeue
size
isempty
Stack Implementations: Using Array
and Linked List
Spring 2012 Programming and Data Structure 50
STACK USING ARRAY
Spring 2012 Programming and Data Structure 51
top
top
PUSH
STACK USING ARRAY
Spring 2012 Programming and Data Structure 52
top
top
POP
Stack: Linked List Structure
Spring 2012 Programming and Data Structure 53
top
PUSH OPERATION
Stack: Linked List Structure
Spring 2012 Programming and Data Structure 54
top
POP OPERATION
Basic Idea
โ€ข In the array implementation, we would:
โ€“ Declare an array of fixed size (which determines the maximum size of
the stack).
โ€“ Keep a variable which always points to the โ€œtopโ€ of the stack.
โ€ข Contains the array index of the โ€œtopโ€ element.
โ€ข In the linked list implementation, we would:
โ€“ Maintain the stack as a linked list.
โ€“ A pointer variable top points to the start of the list.
โ€“ The first element of the linked list is considered as the stack top.
Spring 2012 Programming and Data Structure 56
Declaration
#define MAXSIZE 100
struct lifo
{
int st[MAXSIZE];
int top;
};
typedef struct lifo
stack;
stack s;
struct lifo
{
int value;
struct lifo *next;
};
typedef struct lifo
stack;
stack *top;
Spring 2012 Programming and Data Structure 57
ARRAY LINKED LIST
Stack Creation
void create (stack *s)
{
s->top = -1;
/* s->top points to
last element
pushed in;
initially -1 */
}
void create (stack **top)
{
*top = NULL;
/* top points to NULL,
indicating empty
stack */
}
Spring 2012 Programming and Data Structure 58
ARRAY
LINKED LIST
Pushing an element into the stack
void push (stack *s, int element)
{
if (s->top == (MAXSIZE-1))
{
printf (โ€œn Stack overflowโ€);
exit(-1);
}
else
{
s->top ++;
s->st[s->top] = element;
}
}
Spring 2012 Programming and Data Structure 59
ARRAY
void push (stack **top, int element)
{
stack *new;
new = (stack *) malloc(sizeof(stack));
if (new == NULL)
{
printf (โ€œn Stack is fullโ€);
exit(-1);
}
new->value = element;
new->next = *top;
*top = new;
}
Spring 2012 Programming and Data Structure 60
LINKED LIST
Popping an element from the stack
int pop (stack *s)
{
if (s->top == -1)
{
printf (โ€œn Stack underflowโ€);
exit(-1);
}
else
{
return (s->st[s->top--]);
}
}
Spring 2012 Programming and Data Structure 61
ARRAY
int pop (stack **top)
{
int t;
stack *p;
if (*top == NULL)
{
printf (โ€œn Stack is emptyโ€);
exit(-1);
}
else
{
t = (*top)->value;
p = *top;
*top = (*top)->next;
free (p);
return t;
}
}
Spring 2012 Programming and Data Structure 62
LINKED LIST
Checking for stack empty
int isempty (stack *s)
{
if (s->top == -1)
return 1;
else
return (0);
}
int isempty (stack *top)
{
if (top == NULL)
return (1);
else
return (0);
}
Spring 2012 Programming and Data Structure 63
ARRAY LINKED LIST
Checking for stack full
int isfull (stack *s)
{
if (s->top ==
(MAXSIZEโ€“1))
return 1;
else
return (0);
}
โ€ข Not required for linked list
implementation.
โ€ข In the push() function, we
can check the return value of
malloc().
โ€“ If -1, then memory cannot be
allocated.
Spring 2012 Programming and Data Structure 64
ARRAY LINKED LIST
Example main function :: array
#include <stdio.h>
#define MAXSIZE 100
struct lifo
{
int st[MAXSIZE];
int top;
};
typedef struct lifo stack;
main()
{
stack A, B;
create(&A); create(&B);
push(&A,10);
push(&A,20);
push(&A,30);
push(&B,100); push(&B,5);
printf (โ€œ%d %dโ€, pop(&A),
pop(&B));
push (&A, pop(&B));
if (isempty(&B))
printf (โ€œn B is emptyโ€);
}
Spring 2012 Programming and Data Structure 65
Example main function :: linked list
#include <stdio.h>
struct lifo
{
int value;
struct lifo *next;
};
typedef struct lifo stack;
main()
{
stack *A, *B;
create(&A); create(&B);
push(&A,10);
push(&A,20);
push(&A,30);
push(&B,100);
push(&B,5);
printf (โ€œ%d %dโ€,
pop(&A), pop(&B));
push (&A, pop(&B));
if (isempty(B))
printf (โ€œn B is
emptyโ€);
}
Spring 2012 Programming and Data Structure 66
Queue Implementation using Linked
List
Spring 2012 Programming and Data Structure 67
Basic Idea
โ€ข Basic idea:
โ€“ Create a linked list to which items would be added
to one end and deleted from the other end.
โ€“ Two pointers will be maintained:
โ€ข One pointing to the beginning of the list (point from
where elements will be deleted).
โ€ข Another pointing to the end of the list (point where
new elements will be inserted).
Spring 2012 Programming and Data Structure 68
Front
Rear
DELETION INSERTION
QUEUE: LINKED LIST STRUCTURE
Spring 2012 Programming and Data Structure 69
front rear
ENQUEUE
QUEUE: LINKED LIST STRUCTURE
Spring 2012 Programming and Data Structure 70
front rear
DEQUEUE
QUEUE using Linked List
Spring 2012 Programming and Data Structure 71
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node{
char name[30];
struct node *next;
};
typedef struct node _QNODE;
typedef struct {
_QNODE *queue_front, *queue_rear;
} _QUEUE;
Spring 2012 Programming and Data Structure 72
_QNODE *enqueue (_QUEUE *q, char x[])
{
_QNODE *temp;
temp= (_QNODE *)
malloc (sizeof(_QNODE));
if (temp==NULL){
printf(โ€œBad allocation n");
return NULL;
}
strcpy(temp->name,x);
temp->next=NULL;
if(q->queue_rear==NULL)
{
q->queue_rear=temp;
q->queue_front=
q->queue_rear;
}
else
{
q->queue_rear->next=temp;
q->queue_rear=temp;
}
return(q->queue_rear);
}
Spring 2012 Programming and Data Structure 73
char *dequeue(_QUEUE *q,char x[])
{
_QNODE *temp_pnt;
if(q->queue_front==NULL){
q->queue_rear=NULL;
printf("Queue is empty n");
return(NULL);
}
else{
strcpy(x,q->queue_front->name);
temp_pnt=q->queue_front;
q->queue_front=
q->queue_front->next;
free(temp_pnt);
if(q->queue_front==NULL)
q->queue_rear=NULL;
return(x);
}
}
Spring 2012 Programming and Data Structure 74
void init_queue(_QUEUE *q)
{
q->queue_front= q->queue_rear=NULL;
}
int isEmpty(_QUEUE *q)
{
if(q==NULL) return 1;
else return 0;
}
Spring 2012 Programming and Data Structure 75
main()
{
int i,j;
char command[5],val[30];
_QUEUE q;
init_queue(&q);
command[0]='0';
printf("For entering a name use 'enter <name>'n");
printf("For deleting use 'delete' n");
printf("To end the session use 'bye' n");
while(strcmp(command,"bye")){
scanf("%s",command);
Spring 2012 Programming and Data Structure 76
if(!strcmp(command,"enter")) {
scanf("%s",val);
if((enqueue(&q,val)==NULL))
printf("No more pushing please n");
else printf("Name entered %s n",val);
}
if(!strcmp(command,"delete")) {
if(!isEmpty(&q))
printf("%s n",dequeue(&q,val));
else printf("Name deleted %s n",val);
}
} /* while */
printf("End session n");
}
Problem With Array Implementation
Spring 2012 Programming and Data Structure 77
front rear
rear
ENQUEUE
front
DEQUEUE
Effective queuing storage area of array gets reduced.
Use of circular array indexing
0 N
Queue: Example with Array Implementation
Spring 2012 Programming and Data Structure 78
typedef struct { char name[30];
} _ELEMENT;
typedef struct {
_ELEMENT q_elem[MAX_SIZE];
int rear;
int front;
int full,empty;
} _QUEUE;
#define MAX_SIZE 100
Queue Example: Contd.
Spring 2012 Programming and Data Structure 79
void init_queue(_QUEUE *q)
{q->rear= q->front= 0;
q->full=0; q->empty=1;
}
int IsFull(_QUEUE *q)
{return(q->full);}
int IsEmpty(_QUEUE *q)
{return(q->empty);}
Queue Example: Contd.
Spring 2012 Programming and Data Structure 80
void AddQ(_QUEUE *q, _ELEMENT ob)
{
if(IsFull(q)) {printf("Queue is Full n"); return;}
q->rear=(q->rear+1)%(MAX_SIZE);
q->q_elem[q->rear]=ob;
if(q->front==q->rear) q->full=1; else q->full=0;
q->empty=0;
return;
}
Queue Example: Contd.
Spring 2012 Programming and Data Structure 81
_ELEMENT DeleteQ(_QUEUE *q)
{
_ELEMENT temp;
temp.name[0]='0';
if(IsEmpty(q)) {printf("Queue is EMPTYn");return(temp);}
q->front=(q->front+1)%(MAX_SIZE);
temp=q->q_elem[q->front];
if(q->rear==q->front) q->empty=1; else q->empty=0;
q->full=0;
return(temp);
}
Queue Example: Contd.
Spring 2012 Programming and Data Structure 82
main()
{
int i,j;
char command[5];
_ELEMENT ob;
_QUEUE A;
init_queue(&A);
command[0]='0';
printf("For adding a name use 'add [name]'n");
printf("For deleting use 'delete' n");
printf("To end the session use 'bye' n");
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Queue Example: Contd.
Spring 2012 Programming and Data Structure 83
while (strcmp(command,"bye")!=0){
scanf("%s",command);
if(strcmp(command,"add")==0) {
scanf("%s",ob.name);
if (IsFull(&A))
printf("No more insertion please n");
else {
AddQ(&A,ob);
printf("Name inserted %s n",ob.name);
}
}
Queue Example: Contd.
Spring 2012 Programming and Data Structure 84
if (strcmp(command,"delete")==0) {
if (IsEmpty(&A))
printf("Queue is empty n");
else {
ob=DeleteQ(&A);
printf("Name deleted %s n",ob.name);
}
}
} /* End of while */
printf("End session n");
}

More Related Content

Similar to Wk11-linkedlist.ppt

cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.pptRahulYadav738822
ย 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 dsHanif Durad
ย 
Unit7 C
Unit7 CUnit7 C
Unit7 Carnold 7490
ย 
lect- 3&4.ppt
lect- 3&4.pptlect- 3&4.ppt
lect- 3&4.pptmrizwan38
ย 
Data structure
 Data structure Data structure
Data structureShahariar limon
ย 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Balwant Gorad
ย 
Lec3-Linked list.pptx
Lec3-Linked list.pptxLec3-Linked list.pptx
Lec3-Linked list.pptxFaheemMahmood2
ย 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked ListsAfaq Mansoor Khan
ย 
Singly Linked List
Singly Linked ListSingly Linked List
Singly Linked Listraghavbirla63
ย 
Sorting & Linked Lists
Sorting & Linked ListsSorting & Linked Lists
Sorting & Linked ListsJ.T.A.JONES
ย 
Linked List.pptx
Linked List.pptxLinked List.pptx
Linked List.pptxPoonamPatil120
ย 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure conceptsAkila Krishnamoorthy
ย 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptxjack881
ย 
Circular linked list
Circular linked listCircular linked list
Circular linked listdchuynh
ย 
Stack - PPT Slides.pptx-data sturutures and algorithanms
Stack - PPT Slides.pptx-data sturutures and algorithanmsStack - PPT Slides.pptx-data sturutures and algorithanms
Stack - PPT Slides.pptx-data sturutures and algorithanmsAdithaBuwaneka
ย 

Similar to Wk11-linkedlist.ppt (20)

cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.ppt
ย 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
ย 
Unit7 C
Unit7 CUnit7 C
Unit7 C
ย 
lect- 3&4.ppt
lect- 3&4.pptlect- 3&4.ppt
lect- 3&4.ppt
ย 
Data structure
 Data structure Data structure
Data structure
ย 
Unit 5 linked list
Unit   5 linked listUnit   5 linked list
Unit 5 linked list
ย 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
ย 
Lec3-Linked list.pptx
Lec3-Linked list.pptxLec3-Linked list.pptx
Lec3-Linked list.pptx
ย 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked Lists
ย 
Singly Linked List
Singly Linked ListSingly Linked List
Singly Linked List
ย 
Linked list
Linked listLinked list
Linked list
ย 
Sorting & Linked Lists
Sorting & Linked ListsSorting & Linked Lists
Sorting & Linked Lists
ย 
Unit II Data Structure 2hr topic - List - Operations.pptx
Unit II  Data Structure 2hr topic - List - Operations.pptxUnit II  Data Structure 2hr topic - List - Operations.pptx
Unit II Data Structure 2hr topic - List - Operations.pptx
ย 
Linked List.pptx
Linked List.pptxLinked List.pptx
Linked List.pptx
ย 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
ย 
L7 pointers
L7 pointersL7 pointers
L7 pointers
ย 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptx
ย 
Circular linked list
Circular linked listCircular linked list
Circular linked list
ย 
Stack - PPT Slides.pptx-data sturutures and algorithanms
Stack - PPT Slides.pptx-data sturutures and algorithanmsStack - PPT Slides.pptx-data sturutures and algorithanms
Stack - PPT Slides.pptx-data sturutures and algorithanms
ย 
17 linkedlist (1)
17 linkedlist (1)17 linkedlist (1)
17 linkedlist (1)
ย 

Recently uploaded

CHEAP Call Girls in Pushp Vihar (-DELHI )๐Ÿ” 9953056974๐Ÿ”(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )๐Ÿ” 9953056974๐Ÿ”(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )๐Ÿ” 9953056974๐Ÿ”(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )๐Ÿ” 9953056974๐Ÿ”(=)/CALL GIRLS SERVICE9953056974 Low Rate Call Girls In Saket, Delhi NCR
ย 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto Gonzรกlez Trastoy
ย 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
ย 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
ย 
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธanilsa9823
ย 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
ย 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
ย 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
ย 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
ย 
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female serviceCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
ย 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
ย 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
ย 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
ย 
call girls in Vaishali (Ghaziabad) ๐Ÿ” >เผ’8448380779 ๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธ
call girls in Vaishali (Ghaziabad) ๐Ÿ” >เผ’8448380779 ๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธcall girls in Vaishali (Ghaziabad) ๐Ÿ” >เผ’8448380779 ๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธ
call girls in Vaishali (Ghaziabad) ๐Ÿ” >เผ’8448380779 ๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธDelhi Call girls
ย 
Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...Steffen Staab
ย 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...OnePlan Solutions
ย 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
ย 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
ย 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
ย 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
ย 

Recently uploaded (20)

CHEAP Call Girls in Pushp Vihar (-DELHI )๐Ÿ” 9953056974๐Ÿ”(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )๐Ÿ” 9953056974๐Ÿ”(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )๐Ÿ” 9953056974๐Ÿ”(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )๐Ÿ” 9953056974๐Ÿ”(=)/CALL GIRLS SERVICE
ย 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
ย 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
ย 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
ย 
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธ
ย 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
ย 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
ย 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
ย 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
ย 
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female serviceCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
ย 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
ย 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
ย 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
ย 
call girls in Vaishali (Ghaziabad) ๐Ÿ” >เผ’8448380779 ๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธ
call girls in Vaishali (Ghaziabad) ๐Ÿ” >เผ’8448380779 ๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธcall girls in Vaishali (Ghaziabad) ๐Ÿ” >เผ’8448380779 ๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธ
call girls in Vaishali (Ghaziabad) ๐Ÿ” >เผ’8448380779 ๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธ
ย 
Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spacesย - and Epistemic Querying of RDF-...
ย 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...
ย 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
ย 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
ย 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
ย 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
ย 

Wk11-linkedlist.ppt

  • 1. PDS Class Test 2 โ€ข Date: October 27, 2016 โ€ข Time: 7pm to 8pm โ€ข Marks: 20 (Weightage 50% i.e. max. 10 to the total score) Room Sections No of students V1 Section 8 (All) Section 9 (AE,AG,BT,CE, CH,CS,CY,EC,EE,EX) 101 49 V2 Section 9 (Rest, if not allotted in V1) Section 10 (All) 50 98 V3 Section 11 (All) 98 V4 Section 12 (All) 94 F116 Section 13 (All) 95 F142 Section 14 (All) 96 Autumn 2016 Programming and Data Structure 1
  • 2. Linked List Spring 2012 Programming and Data Structure 2
  • 3. Introduction โ€ข A linked list is a data structure which can change during execution. โ€“ Successive elements are connected by pointers. โ€“ Last element points to NULL. โ€“ It can grow or shrink in size during execution of a program. โ€“ It can be made just as long as required. โ€“ It does not waste memory space. Spring 2012 Programming and Data Structure 3 A B C head
  • 4. โ€ข Keeping track of a linked list: โ€“ Must know the pointer to the first element of the list (called start, head, etc.). โ€ข Linked lists provide flexibility in allowing the items to be rearranged efficiently. โ€“ Insert an element. โ€“ Delete an element. Spring 2012 Programming and Data Structure 4
  • 5. Illustration: Insertion Spring 2012 Programming and Data Structure 5 A A Item to be inserted X X A B C B C curr tmp
  • 6. Pseudo-code for insertion Spring 2012 Programming and Data Structure 6 typedef struct nd { struct item data; struct nd * next; } node; void insert(node *curr) { node * tmp; tmp=(node *) malloc(sizeof(node)); tmp->next=curr->next; curr->next=tmp; }
  • 7. Illustration: Deletion Spring 2012 Programming and Data Structure 7 A B A B C C Item to be deleted curr tmp
  • 8. Pseudo-code for deletion Spring 2012 Programming and Data Structure 8 typedef struct nd { struct item data; struct nd * next; } node; void delete(node *curr) { node * tmp; tmp=curr->next; curr->next=tmp->next; free(tmp); }
  • 9. In essence ... โ€ข For insertion: โ€“ A record is created holding the new item. โ€“ The next pointer of the new record is set to link it to the item which is to follow it in the list. โ€“ The next pointer of the item which is to precede it must be modified to point to the new item. โ€ข For deletion: โ€“ The next pointer of the item immediately preceding the one to be deleted is altered, and made to point to the item following the deleted item. Spring 2012 Programming and Data Structure 9
  • 10. Array versus Linked Lists โ€ข Arrays are suitable for: โ€“ Inserting/deleting an element at the end. โ€“ Randomly accessing any element. โ€“ Searching the list for a particular value. โ€ข Linked lists are suitable for: โ€“ Inserting an element. โ€“ Deleting an element. โ€“ Applications where sequential access is required. โ€“ In situations where the number of elements cannot be predicted beforehand. Spring 2012 Programming and Data Structure 10
  • 11. Types of Lists โ€ข Depending on the way in which the links are used to maintain adjacency, several different types of linked lists are possible. โ€“ Linear singly-linked list (or simply linear list) โ€ข One we have discussed so far. Spring 2012 Programming and Data Structure 11 A B C head
  • 12. โ€“ Circular linked list โ€ข The pointer from the last element in the list points back to the first element. Spring 2012 Programming and Data Structure 12 A B C head
  • 13. โ€“ Doubly linked list โ€ข Pointers exist between adjacent nodes in both directions. โ€ข The list can be traversed either forward or backward. โ€ข Usually two pointers are maintained to keep track of the list, head and tail. Spring 2012 Programming and Data Structure 13 A B C head tail
  • 14. Basic Operations on a List โ€ข Creating a list โ€ข Traversing the list โ€ข Inserting an item in the list โ€ข Deleting an item from the list โ€ข Concatenating two lists into one Spring 2012 Programming and Data Structure 14
  • 15. List is an Abstract Data Type โ€ข What is an abstract data type? โ€“ It is a data type defined by the user. โ€“ Typically more complex than simple data types like int, float, etc. โ€ข Why abstract? โ€“ Because details of the implementation are hidden. โ€“ When you do some operation on the list, say insert an element, you just call a function. โ€“ Details of how the list is implemented or how the insert function is written is no longer required. Spring 2012 Programming and Data Structure 15
  • 16. Conceptual Idea Spring 2012 Programming and Data Structure 16 List implementation and the related functions Insert Delete Traverse
  • 17. Example: Working with linked list โ€ข Consider the structure of a node as follows: struct stud { int roll; char name[25]; int age; struct stud *next; }; /* A user-defined data type called โ€œnodeโ€ */ typedef struct stud node; node *head; Spring 2012 Programming and Data Structure 17
  • 18. Creating a List Spring 2012 Programming and Data Structure 18
  • 19. How to begin? โ€ข To start with, we have to create a node (the first node), and make head point to it. head = (node *) malloc(sizeof(node)); Spring 2012 Programming and Data Structure 19 head age name roll next
  • 20. Contd. โ€ข If there are n number of nodes in the initial linked list: โ€“ Allocate n records, one by one. โ€“ Read in the fields of the records. โ€“ Modify the links of the records so that the chain is formed. Spring 2012 Programming and Data Structure 20 A B C head
  • 21. node *create_list() { int k, n; node *p, *head; printf ("n How many elements to enter?"); scanf ("%d", &n); for (k=0; k<n; k++) { if (k == 0) { head = (node *) malloc(sizeof(node)); p = head; } else { p->next = (node *) malloc(sizeof(node)); p = p->next; } scanf ("%d %s %d", &p->roll, p->name, &p->age); } p->next = NULL; return (head); } Spring 2012 Programming and Data Structure 21
  • 22. โ€ข To be called from main() function as: node *head; โ€ฆโ€ฆโ€ฆ head = create_list(); Spring 2012 Programming and Data Structure 22
  • 23. Traversing the List Spring 2012 Programming and Data Structure 23
  • 24. What is to be done? โ€ข Once the linked list has been constructed and head points to the first node of the list, โ€“ Follow the pointers. โ€“ Display the contents of the nodes as they are traversed. โ€“ Stop when the next pointer points to NULL. Spring 2012 Programming and Data Structure 24
  • 25. void display (node *head) { int count = 1; node *p; p = head; while (p != NULL) { printf ("nNode %d: %d %s %d", count, p->roll, p->name, p->age); count++; p = p->next; } printf ("n"); } Spring 2012 Programming and Data Structure 25
  • 26. โ€ข To be called from main() function as: node *head; โ€ฆโ€ฆโ€ฆ display (head); Spring 2012 Programming and Data Structure 26
  • 27. Inserting a Node in a List Spring 2012 Programming and Data Structure 27
  • 28. How to do? โ€ข The problem is to insert a node before a specified node. โ€“ Specified means some value is given for the node (called key). โ€“ In this example, we consider it to be roll. โ€ข Convention followed: โ€“ If the value of roll is given as negative, the node will be inserted at the end of the list. Spring 2012 Programming and Data Structure 28
  • 29. Contd. โ€ข When a node is added at the beginning, โ€“ Only one next pointer needs to be modified. โ€ข head is made to point to the new node. โ€ข New node points to the previously first element. โ€ข When a node is added at the end, โ€“ Two next pointers need to be modified. โ€ข Last node now points to the new node. โ€ข New node points to NULL. โ€ข When a node is added in the middle, โ€“ Two next pointers need to be modified. โ€ข Previous node now points to the new node. โ€ข New node points to the next node. Spring 2012 Programming and Data Structure 29
  • 30. Spring 2012 Programming and Data Structure 30 void insert (node **head) { int k = 0, rno; node *p, *q, *new; new = (node *) malloc(sizeof(node)); printf ("nData to be inserted: "); scanf ("%d %s %d", &new->roll, new->name, &new->age); printf ("nInsert before roll (-ve for end):"); scanf ("%d", &rno); p = *head; if (p->roll == rno) /* At the beginning */ { new->next = p; *head = new; }
  • 31. Spring 2012 Programming and Data Structure 31 else { while ((p != NULL) && (p->roll != rno)) { q = p; p = p->next; } if (p == NULL) /* At the end */ { q->next = new; new->next = NULL; } else if (p->roll == rno) /* In the middle */ { q->next = new; new->next = p; } } } The pointers q and p always point to consecutive nodes.
  • 32. โ€ข To be called from main() function as: node *head; โ€ฆโ€ฆโ€ฆ insert (&head); Spring 2012 Programming and Data Structure 32
  • 33. Deleting a node from the list Spring 2012 Programming and Data Structure 33
  • 34. What is to be done? โ€ข Here also we are required to delete a specified node. โ€“ Say, the node whose roll field is given. โ€ข Here also three conditions arise: โ€“ Deleting the first node. โ€“ Deleting the last node. โ€“ Deleting an intermediate node. Spring 2012 Programming and Data Structure 34
  • 35. Spring 2012 Programming and Data Structure 35 void delete (node **head) { int rno; node *p, *q; printf ("nDelete for roll :"); scanf ("%d", &rno); p = *head; if (p->roll == rno) /* Delete the first element */ { *head = p->next; free (p); }
  • 36. Spring 2012 Programming and Data Structure 36 else { while ((p != NULL) && (p->roll != rno)) { q = p; p = p->next; } if (p == NULL) /* Element not found */ printf ("nNo match :: deletion failed"); else if (p->roll == rno) /* Delete any other element */ { q->next = p->next; free (p); } } }
  • 37. Few Exercises to Try Out โ€ข Write a function to: โ€“ Concatenate two given list into one big list. node *concatenate (node *head1, node *head2); โ€“ Insert an element in a linked list in sorted order. The function will be called for every element to be inserted. void insert_sorted (node **head, node *element); โ€“ Always insert elements at one end, and delete elements from the other end (first-in first-out QUEUE). void insert_q (node **head, node *element) node *delete_q (node **head) /* Return the deleted node */ Spring 2012 Programming and Data Structure 37
  • 38. A First-in First-out (FIFO) List Spring 2012 Programming and Data Structure 38 Also called a QUEUE In Out A C B A B
  • 39. A Last-in First-out (LIFO) List Spring 2012 Programming and Data Structure 39 In Out A B C C B Also called a STACK
  • 40. Abstract Data Types Spring 2012 Programming and Data Structure 40
  • 41. Example 1 :: Complex numbers struct cplx { float re; float im; } typedef struct cplx complex; complex *add (complex a, complex b); complex *sub (complex a, complex b); complex *mul (complex a, complex b); complex *div (complex a, complex b); complex *read(); void print (complex a); Spring 2012 Programming and Data Structure 41 Structure definition Function prototypes
  • 42. Spring 2012 Programming and Data Structure 42 Complex Number add print mul sub read div
  • 43. Example 2 :: Set manipulation struct node { int element; struct node *next; } typedef struct node set; set *union (set a, set b); set *intersect (set a, set b); set *minus (set a, set b); void insert (set a, int x); void delete (set a, int x); int size (set a); Spring 2012 Programming and Data Structure 43 Structure definition Function prototypes
  • 44. Spring 2012 Programming and Data Structure 44 Set union size minus intersect delete insert
  • 45. Example 3 :: Last-In-First-Out STACK Assume:: stack contains integer elements void push (stack *s, int element); /* Insert an element in the stack */ int pop (stack *s); /* Remove and return the top element */ void create (stack *s); /* Create a new stack */ int isempty (stack *s); /* Check if stack is empty */ int isfull (stack *s); /* Check if stack is full */ Spring 2012 Programming and Data Structure 45
  • 46. Spring 2012 Programming and Data Structure 46 STACK push create pop isfull isempty
  • 47. Contd. โ€ข We shall look into two different ways of implementing stack: โ€“ Using arrays โ€“ Using linked list Spring 2012 Programming and Data Structure 47
  • 48. Example 4 :: First-In-First-Out QUEUE Assume:: queue contains integer elements void enqueue (queue *q, int element); /* Insert an element in the queue */ int dequeue (queue *q); /* Remove an element from the queue */ queue *create(); /* Create a new queue */ int isempty (queue *q); /* Check if queue is empty */ int size (queue *q); /* Return the no. of elements in queue */ Spring 2012 Programming and Data Structure 48
  • 49. Spring 2012 Programming and Data Structure 49 QUEUE enqueue create dequeue size isempty
  • 50. Stack Implementations: Using Array and Linked List Spring 2012 Programming and Data Structure 50
  • 51. STACK USING ARRAY Spring 2012 Programming and Data Structure 51 top top PUSH
  • 52. STACK USING ARRAY Spring 2012 Programming and Data Structure 52 top top POP
  • 53. Stack: Linked List Structure Spring 2012 Programming and Data Structure 53 top PUSH OPERATION
  • 54. Stack: Linked List Structure Spring 2012 Programming and Data Structure 54 top POP OPERATION
  • 55. Basic Idea โ€ข In the array implementation, we would: โ€“ Declare an array of fixed size (which determines the maximum size of the stack). โ€“ Keep a variable which always points to the โ€œtopโ€ of the stack. โ€ข Contains the array index of the โ€œtopโ€ element. โ€ข In the linked list implementation, we would: โ€“ Maintain the stack as a linked list. โ€“ A pointer variable top points to the start of the list. โ€“ The first element of the linked list is considered as the stack top. Spring 2012 Programming and Data Structure 56
  • 56. Declaration #define MAXSIZE 100 struct lifo { int st[MAXSIZE]; int top; }; typedef struct lifo stack; stack s; struct lifo { int value; struct lifo *next; }; typedef struct lifo stack; stack *top; Spring 2012 Programming and Data Structure 57 ARRAY LINKED LIST
  • 57. Stack Creation void create (stack *s) { s->top = -1; /* s->top points to last element pushed in; initially -1 */ } void create (stack **top) { *top = NULL; /* top points to NULL, indicating empty stack */ } Spring 2012 Programming and Data Structure 58 ARRAY LINKED LIST
  • 58. Pushing an element into the stack void push (stack *s, int element) { if (s->top == (MAXSIZE-1)) { printf (โ€œn Stack overflowโ€); exit(-1); } else { s->top ++; s->st[s->top] = element; } } Spring 2012 Programming and Data Structure 59 ARRAY
  • 59. void push (stack **top, int element) { stack *new; new = (stack *) malloc(sizeof(stack)); if (new == NULL) { printf (โ€œn Stack is fullโ€); exit(-1); } new->value = element; new->next = *top; *top = new; } Spring 2012 Programming and Data Structure 60 LINKED LIST
  • 60. Popping an element from the stack int pop (stack *s) { if (s->top == -1) { printf (โ€œn Stack underflowโ€); exit(-1); } else { return (s->st[s->top--]); } } Spring 2012 Programming and Data Structure 61 ARRAY
  • 61. int pop (stack **top) { int t; stack *p; if (*top == NULL) { printf (โ€œn Stack is emptyโ€); exit(-1); } else { t = (*top)->value; p = *top; *top = (*top)->next; free (p); return t; } } Spring 2012 Programming and Data Structure 62 LINKED LIST
  • 62. Checking for stack empty int isempty (stack *s) { if (s->top == -1) return 1; else return (0); } int isempty (stack *top) { if (top == NULL) return (1); else return (0); } Spring 2012 Programming and Data Structure 63 ARRAY LINKED LIST
  • 63. Checking for stack full int isfull (stack *s) { if (s->top == (MAXSIZEโ€“1)) return 1; else return (0); } โ€ข Not required for linked list implementation. โ€ข In the push() function, we can check the return value of malloc(). โ€“ If -1, then memory cannot be allocated. Spring 2012 Programming and Data Structure 64 ARRAY LINKED LIST
  • 64. Example main function :: array #include <stdio.h> #define MAXSIZE 100 struct lifo { int st[MAXSIZE]; int top; }; typedef struct lifo stack; main() { stack A, B; create(&A); create(&B); push(&A,10); push(&A,20); push(&A,30); push(&B,100); push(&B,5); printf (โ€œ%d %dโ€, pop(&A), pop(&B)); push (&A, pop(&B)); if (isempty(&B)) printf (โ€œn B is emptyโ€); } Spring 2012 Programming and Data Structure 65
  • 65. Example main function :: linked list #include <stdio.h> struct lifo { int value; struct lifo *next; }; typedef struct lifo stack; main() { stack *A, *B; create(&A); create(&B); push(&A,10); push(&A,20); push(&A,30); push(&B,100); push(&B,5); printf (โ€œ%d %dโ€, pop(&A), pop(&B)); push (&A, pop(&B)); if (isempty(B)) printf (โ€œn B is emptyโ€); } Spring 2012 Programming and Data Structure 66
  • 66. Queue Implementation using Linked List Spring 2012 Programming and Data Structure 67
  • 67. Basic Idea โ€ข Basic idea: โ€“ Create a linked list to which items would be added to one end and deleted from the other end. โ€“ Two pointers will be maintained: โ€ข One pointing to the beginning of the list (point from where elements will be deleted). โ€ข Another pointing to the end of the list (point where new elements will be inserted). Spring 2012 Programming and Data Structure 68 Front Rear DELETION INSERTION
  • 68. QUEUE: LINKED LIST STRUCTURE Spring 2012 Programming and Data Structure 69 front rear ENQUEUE
  • 69. QUEUE: LINKED LIST STRUCTURE Spring 2012 Programming and Data Structure 70 front rear DEQUEUE
  • 70. QUEUE using Linked List Spring 2012 Programming and Data Structure 71 #include <stdio.h> #include <stdlib.h> #include <string.h> struct node{ char name[30]; struct node *next; }; typedef struct node _QNODE; typedef struct { _QNODE *queue_front, *queue_rear; } _QUEUE;
  • 71. Spring 2012 Programming and Data Structure 72 _QNODE *enqueue (_QUEUE *q, char x[]) { _QNODE *temp; temp= (_QNODE *) malloc (sizeof(_QNODE)); if (temp==NULL){ printf(โ€œBad allocation n"); return NULL; } strcpy(temp->name,x); temp->next=NULL; if(q->queue_rear==NULL) { q->queue_rear=temp; q->queue_front= q->queue_rear; } else { q->queue_rear->next=temp; q->queue_rear=temp; } return(q->queue_rear); }
  • 72. Spring 2012 Programming and Data Structure 73 char *dequeue(_QUEUE *q,char x[]) { _QNODE *temp_pnt; if(q->queue_front==NULL){ q->queue_rear=NULL; printf("Queue is empty n"); return(NULL); } else{ strcpy(x,q->queue_front->name); temp_pnt=q->queue_front; q->queue_front= q->queue_front->next; free(temp_pnt); if(q->queue_front==NULL) q->queue_rear=NULL; return(x); } }
  • 73. Spring 2012 Programming and Data Structure 74 void init_queue(_QUEUE *q) { q->queue_front= q->queue_rear=NULL; } int isEmpty(_QUEUE *q) { if(q==NULL) return 1; else return 0; }
  • 74. Spring 2012 Programming and Data Structure 75 main() { int i,j; char command[5],val[30]; _QUEUE q; init_queue(&q); command[0]='0'; printf("For entering a name use 'enter <name>'n"); printf("For deleting use 'delete' n"); printf("To end the session use 'bye' n"); while(strcmp(command,"bye")){ scanf("%s",command);
  • 75. Spring 2012 Programming and Data Structure 76 if(!strcmp(command,"enter")) { scanf("%s",val); if((enqueue(&q,val)==NULL)) printf("No more pushing please n"); else printf("Name entered %s n",val); } if(!strcmp(command,"delete")) { if(!isEmpty(&q)) printf("%s n",dequeue(&q,val)); else printf("Name deleted %s n",val); } } /* while */ printf("End session n"); }
  • 76. Problem With Array Implementation Spring 2012 Programming and Data Structure 77 front rear rear ENQUEUE front DEQUEUE Effective queuing storage area of array gets reduced. Use of circular array indexing 0 N
  • 77. Queue: Example with Array Implementation Spring 2012 Programming and Data Structure 78 typedef struct { char name[30]; } _ELEMENT; typedef struct { _ELEMENT q_elem[MAX_SIZE]; int rear; int front; int full,empty; } _QUEUE; #define MAX_SIZE 100
  • 78. Queue Example: Contd. Spring 2012 Programming and Data Structure 79 void init_queue(_QUEUE *q) {q->rear= q->front= 0; q->full=0; q->empty=1; } int IsFull(_QUEUE *q) {return(q->full);} int IsEmpty(_QUEUE *q) {return(q->empty);}
  • 79. Queue Example: Contd. Spring 2012 Programming and Data Structure 80 void AddQ(_QUEUE *q, _ELEMENT ob) { if(IsFull(q)) {printf("Queue is Full n"); return;} q->rear=(q->rear+1)%(MAX_SIZE); q->q_elem[q->rear]=ob; if(q->front==q->rear) q->full=1; else q->full=0; q->empty=0; return; }
  • 80. Queue Example: Contd. Spring 2012 Programming and Data Structure 81 _ELEMENT DeleteQ(_QUEUE *q) { _ELEMENT temp; temp.name[0]='0'; if(IsEmpty(q)) {printf("Queue is EMPTYn");return(temp);} q->front=(q->front+1)%(MAX_SIZE); temp=q->q_elem[q->front]; if(q->rear==q->front) q->empty=1; else q->empty=0; q->full=0; return(temp); }
  • 81. Queue Example: Contd. Spring 2012 Programming and Data Structure 82 main() { int i,j; char command[5]; _ELEMENT ob; _QUEUE A; init_queue(&A); command[0]='0'; printf("For adding a name use 'add [name]'n"); printf("For deleting use 'delete' n"); printf("To end the session use 'bye' n"); #include <stdio.h> #include <stdlib.h> #include <string.h>
  • 82. Queue Example: Contd. Spring 2012 Programming and Data Structure 83 while (strcmp(command,"bye")!=0){ scanf("%s",command); if(strcmp(command,"add")==0) { scanf("%s",ob.name); if (IsFull(&A)) printf("No more insertion please n"); else { AddQ(&A,ob); printf("Name inserted %s n",ob.name); } }
  • 83. Queue Example: Contd. Spring 2012 Programming and Data Structure 84 if (strcmp(command,"delete")==0) { if (IsEmpty(&A)) printf("Queue is empty n"); else { ob=DeleteQ(&A); printf("Name deleted %s n",ob.name); } } } /* End of while */ printf("End session n"); }