linked list (1)
linked list (1)
Content
1) Dynamic size
2) Ease of insertion/deletion
Drawbacks:
1) Random access is not allowed.
2) Extra memory space for a pointer is required
with each element of the list.
3) Not cache friendly
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.
head
– It does not waste memory space.
A B C
Linked List
• Keeping track of a linked list:
– Must know the pointer to the first element of the
list (called start, head, etc.).
C
Creating a node
struct node
{
head
int data;
A struct node *next;
} * newNode;
//Create a new node
C
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
if(head == NULL)
{
//
If list is empty, both head and tail will point to ne
w node
head = newNode;
tail = newNode;
}
void addNode(int data)
{
struct node *newNode = (struct node*)malloc(sizeof(struct nod
e));
newNode->data = data;
newNode->next = NULL;
if(head == NULL)
{
head = newNode;
tail = newNode;
}
else {
tail->next = newNode;
tail = newNode;
}
}
Creating a node
struct node
{
head
int data;
A struct node *next;
};
head
A B C
Structure Variable
struct node *head, *tail = NULL;
Illustration: Insertion
A B C
Item to be
tmp X inserted
A B C
curr
X
Pseudo-code for insertion
typedef struct nd {
struct item data;
struct nd * next;
} node;
tmp=(node *) malloc(sizeof(node));
tmp->next=curr->next;
curr->next=tmp;
}
Illustration: Deletion
Item to be deleted
A B C
tmp
curr
A B C
Pseudo-code for deletion
typedef struct nd {
struct item data;
struct nd * next;
} node;
A B C
– Circular linked list
• The pointer from the last element in the list points back
to the first element.
head
A B C
– 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
head tail
the list, head and tail.
A B C
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
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.
Conceptual Idea
Insert
List
implementation
Delete and the
related functions
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;
};
name next
age
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
head formed.
A B C
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);
}
• To be called from main() function as:
node *head;
………
head = create_list();
Traversing the List
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.
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");
}
• To be called from main() function as:
node *head;
………
display (head);
Inserting a Node in a List
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.
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.
Insert a node at the beginning
Insert a node at the beginning
• Step 1: IF PTR = NULL
• Write OVERFLOW
Go to Step 7
[END OF IF]
• Step 2: SET NEW_NODE = PTR
• Step 3: SET PTR = PTR → NEXT
• Step 4: SET NEW_NODE → DATA = VAL
• Step 5: SET NEW_NODE → NEXT = HEAD
• Step 6: SET HEAD = NEW_NODE
• Step 7: EXIT
void beginsert(int item)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node *
));
if(ptr == NULL)
{
printf("\nOVERFLOW\n");
}
else
{
ptr->data = item;
ptr->next = head;
head = ptr;
printf("\nNode inserted\n");
}
• To be called from main() function as:
node *head;
………
insert (&head);
Polynomial
4x7 + 12x2 + 45
struct Node{
int coeff;
int pow;
struct Node *next;
};
• Input: 1st number = 5x2 + 4x1 + 2x0
• 2nd number = -5x1 - 5x0
• Output: 5x2-1x1-3x0
• Input: 1st number = 5x3 + 4x2 + 2x0
• 2nd number = 5x^1 - 5x^0
• Output: 5x3 + 4x2 + 5x1 - 3x0
Algorithm
• If both the numbers are null then return
• else if compare the power, if same then add the
coefficients and recursively call addPolynomials on
the next elements of both the numbers.
• else if the power of first number is greater then print
the current element of first number and recursively
call addPolynomial on the next element of the first
number and current element of the second number.
• else print the current element of the second number
and recursively call addPolynomial on the current
element of first number and next element of second
number.
Sparse Matrix Representation
Deleting a node from the list
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.
void delete (node **head)
{
int rno;
node *p, *q;
p = *head;
if (p->roll == rno)
/* Delete the first element */
{
*head = p->next;
free (p);
}
else
{
while ((p != NULL) && (p->roll != rno))
{
q = p;
p = p->next;
}
B A
C B A
C B A B C
Also called a
STACK
Abstract Data Types
Example 1 :: Complex numbers
struct cplx {
float re; Structure
float im;
definition
}
typedef struct cplx complex;
sub
mul Complex
Number
div
read
print
Example 2 :: Set manipulation
struct node {
int element; Structure
struct node *next;
definition
}
typedef struct node set;
intersect
minus
Set
insert
delete
size
Example 3 :: Last-In-First-Out STACK
Assume:: stack contains integer elements
pop
create
STACK
isempty
isfull
Contd.
• We shall look into two different ways of
implementing stack:
– Using arrays
– Using linked list
Example 4 :: First-In-First-Out QUEUE
Assume:: queue contains integer elements
dequeue
create
QUEUE
isempty
size
Stack Implementations: Using Array and
Linked List
STACK USING ARRAY
PUSH
top
top
STACK USING ARRAY
PO
P
top
top
Stack: Linked List Structure
PUSH OPERATION
top
Stack: Linked List Structure
POP OPERATION
top
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.
Declaration
#define MAXSIZE 100 struct lifo
{
struct lifo int value;
{ struct lifo *next;
int st[MAXSIZE]; };
int top; typedef struct lifo
}; stack;
typedef struct lifo
stack; stack *top;
stack s;
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;
}
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--]);
}
}
ARRAY
int pop (stack **top)
{
int t;
stack *p;
if (*top == NULL)
{
printf (“\n Stack is empty”);
exit(-1); LINKED LIST
}
else
{
t = (*top)->value;
p = *top;
*top = (*top)->next;
free (p);
return t;
}
}
Checking for stack empty
int isempty (stack *s) int isempty (stack *top)
{ {
if (s->top == -1) if (top == NULL)
return 1; return (1);
else else
return (0); return (0);
} }
ENQUEUE
front rear
QUEUE: LINKED LIST STRUCTURE
DEQUEUE
front rear
QUEUE using Linked List
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node{
char name[30];
struct node *next;
};
typedef struct {
_QNODE *queue_front, *queue_rear;
} _QUEUE;
_QNODE *enqueue (_QUEUE *q, char x[])
{
if(q->queue_rear==NULL)
_QNODE *temp;
{
temp= (_QNODE *)
q->queue_rear=temp;
malloc (sizeof(_QNODE));
q->queue_front=
if (temp==NULL){
q->queue_rear;
printf(“Bad allocation \n");
}
return NULL;
else
}
{
strcpy(temp->name,x);
q->queue_rear->next=temp;
temp->next=NULL;
q->queue_rear=temp;
}
return(q->queue_rear);
}
char *dequeue(_QUEUE *q,char x[])
{ else{
_QNODE *temp_pnt; strcpy(x,q->queue_front->name);
temp_pnt=q->queue_front;
if(q->queue_front==NULL){ q->queue_front=
q->queue_rear=NULL; q->queue_front->next;
printf("Queue is empty \n"); free(temp_pnt);
return(NULL); if(q->queue_front==NULL)
} q->queue_rear=NULL;
return(x);
}
}
void init_queue(_QUEUE *q)
{
q->queue_front= q->queue_rear=NULL;
}
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);
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
ENQUEUE DEQUEUE
0 N
front
front rearrear
typedef struct {
_ELEMENT q_elem[MAX_SIZE];
int rear;
int front;
int full,empty;
} _QUEUE;
Queue Example: Contd.
void init_queue(_QUEUE *q)
{q->rear= q->front= 0;
q->full=0; q->empty=1;
}
q->rear=(q->rear+1)%(MAX_SIZE);
q->q_elem[q->rear]=ob;
return;
}
Queue Example: Contd.
_ELEMENT DeleteQ(_QUEUE *q)
{
_ELEMENT temp;
temp.name[0]='\0';
q->front=(q->front+1)%(MAX_SIZE);
temp=q->q_elem[q->front];
return(temp);
Queue Example: Contd.
main() #include <stdio.h>
{ #include <stdlib.h>
int i,j; #include
char command[5]; <string.h>
_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");
Queue Example: Contd.
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.
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");
}