0% found this document useful (0 votes)
89 views128 pages

15IT305 Data Structures and Algorithms

Linked lists allow dynamic memory allocation. Each node contains a data field and a pointer to the next node. This allows lists to grow and shrink easily during program execution. Linked lists have advantages over arrays for insertion and deletion since elements don't need to be shifted. Common list operations include insertion, deletion, traversal, search, and deletion by key.

Uploaded by

Harish ram
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views128 pages

15IT305 Data Structures and Algorithms

Linked lists allow dynamic memory allocation. Each node contains a data field and a pointer to the next node. This allows lists to grow and shrink easily during program execution. Linked lists have advantages over arrays for insertion and deletion since elements don't need to be shifted. Common list operations include insertion, deletion, traversal, search, and deletion by key.

Uploaded by

Harish ram
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 128

15IT305 

 
DATA STRUCTURES AND ALGORITHMS

Linked List - Introduction


ADT - FUNDAMENTALS
ADT is basically a set of operations.

The implementation of operation is not defined and it is left to


the
user.
ADT ADVANTAGES

Encapsulation
The user need not worry out implementation of the operation

Flexibility
The operations may be implemented differently for different
applications.
PRIMARY ADTs

• LIST
• STACK
• QUEUE
SO2-Linked List ADT
A linked list is a series of connected nodes (or links) where each
node is a data structure.

Dynamically allocated data structures can be linked together to


form a chain.

A linked list can grow or shrink in size as the program runs.


This is possible because the nodes in a linked list are dynamically
allocated.
What does the memory look like?
A B C 

Head

a1 a2 a3 a4

Memory a1 800 a2 712 a3 992 a4 0


Content

Memory
Address 1000 800 712 992

*
Advantages of Linked Lists over Arrays

Linked lists are more complex to code and manage than arrays, but
they have some distinct advantages.
a) linked list can easily grow and shrink in size
The programmer doesn’t need to know how many nodes will
be in the list. They are created in memory as needed.
b) speed of insertion or deletion from the list
Inserting and deleting elements into and out of arrays
requires
moving elements of the array. When a node is inserted, or
deleted from a linked list, none of the other nodes have to be
moved.
LISTof elements
Collection

Types

1.Singly linked list


2.Doubly linked list
3.Circularly linked list
• Singly circular linked list
• Doubly circular linked list
SO3-Composition of a Linked List

Each node in the linked list contains -

a) One or more members that represent data (e.g. inventory


records, customer names, addresses, telephone numbers,
etc).

b) A pointer, that can point to another node.

Data Members Pointer


Composition of a Linked List

A linked list is called “linked” because each node in the series


(i.e. the chain) has a pointer to the next node in the list, e.g.

a) The list head is a pointer to the first node in the list.


b) Each node in the list points to the next node in the list.
c) The last node points to NULL (the usual way to signify the end).

pHead pTail

struct Node { struct Node { struct Node {


char element; char element; char element;
NULL
Node *next;
*next; Node *next;
*next; Node *next;
*next;
}; }; };
Pointer Implementation (Linked
List)
• First, define a Node.

struct Node {
double data; // data
a
struct Node* next; // pointer to next
};

“self-referentiality”

*
Linked list representation
#include<stdio.h> int main()
#include<stdlib.h> {
struct node int i,n,x;
{ void insert(int);
void display();
int data; printf("list size is\n");
struct node* link; scanf("%d",&n);
}; printf("Enter the array values\n");
struct node* head; for(i=0;i<n;i++)
{
scanf("%d",&x);
insert(x);
}
display();
getch();
return 0;
}
void insert(int a)
{
struct node* temp=(node*)malloc(sizeof(struct node));
temp->data=a;
temp->link=head;
head=temp;
}
void display()
{
struct node* t=head;
while(t!= NULL)
{
printf("%d\t",t->data);
t=t->link;
} }
FAQ -1
1.A linear collection of data elements where the linear node is
given by means of pointer is called
(A) linked list (B) node list (C) primitive list
(D) None of these

2. Data is otherwise known as ____________.


 
FAQ 2

1.In data structure, data may be of __ types.


a.1 b.4 c.3 4.2

2. Single and non-decomposable data is called


______________.
a)Textual data b)Composite data
c)Numeric data d)Atomic data
Operations on List
Following are the basic operations supported by a list.
•Insertion − add an element at the beginning of the
list.
•Deletion − delete an element at the beginning of the
list.
•Display − displaying complete list.
•Search − search an element using given key.
•Delete − delete an element using given key.
Linked list representation
Insertion Operation

Insertion is a three step process −


•Create a new Link with provided data.
•Point New Link to old First Link.
•Point First Link to this New Link.
Insert at first
Inserting node at start in the SLL (Steps)

•Create New Node


•Fill Data into “Data Field“
•Make it’s “Pointer” or “Next Field” as NULL
•Attach This newly Created node to Start
•Make newnode as Starting node
Insert at first
#include<stdlib.h> void main()
struct node {
{ struct node *newnode,*current;
int data; new_node=(struct node *)malloc(sizeof(
struct node *next; struct node));
}*start=NULL; printf(“\nEnter the data : ");
scanf("%d",&new_node->data);
new_node->next=NULL;
Insert cont…
if(start == NULL)
{
start = new_node;
current = new_node;
}
else
{
new_node->next=start;
start=new_node;
}
Insert at last
Inserting node at start in the SLL (Steps)
•Create New Node
•Fill Data into “Data Field“
•Make it’s “Pointer” or “Next Field” as NULL
•Node is to be inserted at Last Position so we
need to traverse SLL upto Last Node.
•Make link between last node and newnode
Insert at end
void insert_at_end()
{
struct node *new_node,*current;
new_node=(struct node *)malloc(sizeof(struct node));
printf("nEnter the data : ");
scanf("%d",&new_node->data);
new_node->next=NULL;
if(start==NULL)
{
start=new_node;
current=new_node;
}
else {
temp = start;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = new_node;
}
}
Insert at middle
struct node new_node,*current,*temp,*temp1;
new_node=(struct node *)malloc(sizeof(struct node));
printf("nEnter the data : ");
scanf("%d",&new_node->data);
new_node->next=NULL;

printf("nEnter the position : ");


scanf("%d",&pos);
if(start==NULL)
{ start=new_node;
current=new_node; }
else
{
temp = start;
for(i=1;i< pos-1;i++)
{
temp = temp->next;
}
temp1=temp->next;
temp->next = new_node;
new_node->next=temp1;
}
}
Deletion Operation
Deletion is a two step process −
•Get the Link pointed by First Link as Temp Link.
•Point First Link to Temp Link's Next Link.
Code to delete
void del_beg()
{
struct node *temp;
temp = start;
start = start->next;
free(temp);
printf("nThe Element deleted Successfully ");
}
FAQ -1
1.What would be the asymptotic time complexity to add an element
in the linked list?

a)O(1)
b)O(n)
c)O(n2
d) None

2. Each node in singly linked list has ........ fields.


a) 2 b) 3 c) 1 d) 4

 
FAQ 2

1.In linked lists there are no NULL links in


A. single linked list
B. linear doubly linked list
C. circular linked list
D. linked list

2. In a linked list the .......... field contains the address of


next element in the list.
A. Link field B. Next element field C. Start field
D. Info field
Deletion Operation
Deletion is a two step process −
•Get the Link pointed by First Link as Temp Link.
•Point First Link to Temp Link's Next Link.
Code to delete
void del_beg()
{
struct node *temp;
temp = start;
start = start->next;
free(temp);
printf("nThe Element deleted Successfully ");
}
Navigation Operation
Navigation is a recursive step process and is basis of many operations like
search, delete etc.
void display()
{
struct node *temp; //Declare temp
temp=start; //Assign Starting Address to temp
while(temp!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}
}
Doubly Linked List
• info: the user's data
• next, back: the address of the next and previous node in the list
• We no longer need to use prevLocation (we can get the predecessor of a node
using its back member)

.back .info .next


Defining a Structure

Struct node
{
int data;
struct node *prevptr;
struct node *nextptr;
};
struct node *root=null;
Insertion routine
Display routine
Circular Linked List
 A Circular Linked List is a special type of Linked List
 It supports traversing from the end of the list to the beginning
by making the last node point back to the head of the list
 A Rear pointer is often used instead of a Head pointer
Applications of List
• Polynomials
• Radix sort
• Multilist
Polynomials
• A polynomial is a sum of terms. Each term consists of a
coefficient and a (common) variable raised to an
exponent.
• perform operations on polynomials.
Example: 4x3 + 5x – 10

struct node

float coefficient;
int exponent;
struct node *next;
Operations on polynomials
Adding polynomials
(3x5 – 9x3 + 4x2) + (–8x5 + 8x3 + 2)
= 3x5 – 8x5 – 9x3 + 8x3 + 4x2 + 2
= –5x5 – x3 + 4x2 + 2
Multiplying polynomials
(2x – 3)*(2x2 + 3x – 2)
= 2x(2x2 + 3x – 2) – 3(2x2 + 3x – 2)
= 4x3 + 6x2 – 4x – 6x2 – 9x+ 6
= 4x3 – 13x+ 6
Linked List representation
Radix sort
• repeatedly sorts by digit—perform multiple
bucket sorts on S starting with the rightmost
digit
• If maximum value is 999999, only ten buckets
(not 1 million) will be necessary

Number of passes (bucket sort stages) will depend on the


number of digits in the maximum value
Example: first pass
12 58 37 64 52 36 99 63 18 9 20 88 47

58
12 37 18
20 52 63 64 36 47 88 99

20 12 52 63 64 36 37 47 58 18 88 9 99
Example: second pass
20 12 52 63 64 36 37 47 58 18 88 9 99

12 36 52 63
18 20 37 47 58 64 88 99

9 12 18 20 36 37 47 52 58 63 64 88 99
Example: 1 and 2 passes
st nd

12 58 37 64 52 36 99 63 18 9 20 88 47

sort by rightmost digit

20 12 52 63 64 36 37 47 58 18 88 9 99

sort by leftmost digit

9 12 18 20 36 37 47 52 58 63 64 88 99
FAQ -1
1.To insert a new node in linked list free node will be available
in ........
A. Available list B. Avail list C. Free node list
D. Memory space list

2. A linear list in which each node has point to the predecessor


and successors nodes is called ........

A. singly linked list B. circular linked list


C. doubly linked list D. linear linked list

 
FAQ 2
1. In a circular linked list

a) Components are all linked together in some sequential


manner.
b) There is no beginning and no end.
c) Components are arranged hierarchically.
d) Forward and backward traversal within the list is
permitted.
2. Consider the following definition in c programming language

struct node

int data;
struct node * next;

typedef struct node NODE;


NODE *ptr;

Which of the following c code is used to create new node?

a) ptr=(NODE*)malloc(sizeof(NODE));
b) ptr=(NODE*)malloc(NODE);
c) ptr=(NODE*)malloc(sizeof(NODE*));
d) ptr=(NODE)malloc(sizeof(NODE));
STACK ADT
STACK

A stack is a restricted linear list in which all additions and


deletions are made at one end, the top.

If we insert a series of data items into a stack and then


remove them, the order of the data is reversed. This
reversing attribute is why stacks are known as last in, first
out (LIFO) data structures.

Three representations of stacks


Operations on stacks

There are four basic operations creating a stack, push, pop


and empty.

The stack operation


The stack operation creates an empty stack. The following
shows the format.

Stack operation
The push operation
The push operation inserts an item at the top of the stack.
The following shows the format.

Push operation
The pop operation
The pop operation deletes the item at the top of the stack.
The following shows the format.

Pop operation
The empty operation
The empty operation checks the status of the stack. The
following shows the format.

This operation returns true if the stack is empty and false if


the stack is not empty.
Stack ADT

We define a stack as an ADT as shown below:


The figure shows a segment of an algorithm that applies the
previously defined operations on a stack S.
Stack applications

•Balancing Symbols
•Infix to Postfix
•Evaluation of expression
•Recursion
STACK USING ARRAYS
do    {
# include <stdio.h>
       printf("[1].PUSH [2].POP
# include <conio.h>
[3].Display [4].Exit");
# define SIZE 10
    printf("Enter your choice
int arr[SIZE], top = -1, i ; [1-4] : ") ;
void push() ;        scanf("%d", &ch) ;
void pop() ;        switch(ch)
void display() ;        {
void main()            case 1 :
{                push() ;
   int ch ;                break ;
   clrscr() ;            case 2 :
                 pop() ;
               break ;
  case 3 :
               display() ;
               break ;
           case 4 :
               break ;
           default :
               printf("Invalid option") ;
               getch() ;
       }
   } while(ch != 4) ;
   getch() ;
}
Push operation
void push()
{
if(top == SIZE - 1)
{
printf("Stack is full (overflow)") ;
getch() ;
return ;
}
top++ ;
printf("Enter the element to PUSH : ") ;
scanf("%d", &arr[top]) ;
}
Pop operation
void pop()
{
if(top == -1)
{
printf("Stack is empty (underflow)") ;
getch() ;
return ;
}
printf("The POP element is : %d", arr[top]) ;
getch() ;
top-- ;
}
Display operation
void display()
{
if(top == -1)
{
printf("Stack is empty (underflow)") ;
getch() ;
return ;
}
printf("The elements in stack are :TOP") ;
for(i = top ; i >= 0 ; i--)
printf(" -> %d", arr[i]) ;
getch() ;
}
Assessment
1. In what order the elements of a pushdown stack are
accessed
a. LILO b. LIFO c. FIFO d. None
2. The operation for removing an entry from a stack is
traditionally called:
A. delete B. peek C. pop D. remove
3. The operation for adding an entry to a stack is
traditionally called:
A. add B. append C. insert D. push
4. Which of the following stack operations could result in
stack underflow?
A. is_empty B. pop C. push d. None
IMPLEMENTATION OF STACK
USING LINKED LIST
List Stack Example

top

6
List Stack Example

top

6
List Stack Example

top 7

6
List Stack Example

top 7

6
List Stack Example

top 7

6
List Stack Example

top 7

6
Linked List Implementation of
stack
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
Struct node
{
char data;
node *next;
};
node *top=NULL,*newnode,*temp;
PUSH & POP Routine
char pop()
Void push(char data) {
{ if(top==NULL)
newnode=(node return ‘\0’;
*)malloc(sizeof(node)); else
newnode->data=data; {
char ch=top->data;
newnode->next=top;
temp=top;
top=newnode; top=top->next;
} free(temp);
return ch; }
}
Display & Main Routine
void display()
void main()
{
if(top==NULL) {
printf(“\n The stack has no
data\n”); push(a);
else push(b);
{
temp=top; display();
While(temp!=NULL) pop();
{
display();
printf(“%c\n”,temp->data”);
temp=temp-
push(c);
>next; push(d);
}
} display(); }
}
Algorithm for Infix to Postfix conversion

Start scanning the infix expression from left to


right
If operand is encountered just output the value
If operator is encountered do the following
Pop until stack top has higher or equal precedence
than the current operator and send the popped
operators to the output
Push current operator to stack
Contd..
Handling the parenthesis

Left parenthesis is always pushed into the stack

If right parenthesis is encountered, stack is popped


until the left parenthesis

Both left and right parenthesis are discarded


Example
1. ((A+B) /(C-D))
Ans: AB+CD-/
1. A+ (B*C)
Ans: ABC*+
1. (A+B)*C
Ans:AB+C*
Infix to postfix conversion
infixVect
(a+b-c)*d–(e+f)

postfixVect
Infix to postfix conversion
stackVect

infixVect
a+b-c)*d–(e+f)

postfixVect

(
Infix to postfix conversion
stackVect

infixVect
+b-c)*d–(e+f)

postfixVect
a

(
Infix to postfix conversion
stackVect

infixVect
b-c)*d–(e+f)

postfixVect
a

+
(
Infix to postfix conversion
stackVect

infixVect
-c)*d–(e+f)

postfixVect
ab

+
(
Infix to postfix conversion
stackVect

infixVect
c)*d–(e+f)

postfixVect
ab+

-
(
Infix to postfix conversion
stackVect

infixVect
)*d–(e+f)

postfixVect
ab+c

-
(
Infix to postfix conversion
stackVect

infixVect
*d–(e+f)

postfixVect
ab+c-
Infix to postfix conversion
stackVect

infixVect
d–(e+f)

postfixVect
ab+c-

*
Infix to postfix conversion
stackVect

infixVect
–(e+f)

postfixVect
ab+c-d

*
Infix to postfix conversion
stackVect

infixVect
(e+f)

postfixVect
ab+c–d*

-
Infix to postfix conversion
stackVect

infixVect
e+f)

postfixVect
ab+c–d*

(
-
Infix to postfix conversion
stackVect

infixVect
+f)

postfixVect
ab+c–d*e

(
-
Infix to postfix conversion
stackVect

infixVect
f)

postfixVect

+ ab+c–d*e

(
-
Infix to postfix conversion
stackVect

infixVect
)

postfixVect

+ ab+c–d*ef

(
-
Infix to postfix conversion
stackVect

infixVect

postfixVect
ab+c–d*ef+

-
Infix to postfix conversion
stackVect

infixVect

postfixVect
ab+c–d*ef+-
Algorithm for evaluating postfix
expressions
Start scanning the postfix expressions from left to right
If operand is encountered then push it on to the stack
If an operator is encountered, pop last two operands
from the stack, apply the operator on the operands
and then push the resultant value on to the stack
Finally the stack must contain the single value which is
the result
1. 5 6 2 + * 12 4 / -
Ans: 37
2. 6 5 2 3 + 8 * + 3 + *
Ans: 288
3. (A*B)+(C/D) where A=3, B=2, C=25, D=5)
Ans:11
SO1-QUEUES

A queue is a linear list in which data can only be


inserted at one end, called the rear, and deleted from the
other end, called the front. These restrictions ensure that
the data is processed through the queue in the order in
which it is received. In other words, a queue is a first in,
first out (FIFO) structure.
Operations on queues

Although we can define many operations for a queue, four


are basic: queue, enqueue, dequeue and empty, as defined
below.
The queue operation
The queue operation creates an empty queue. The following
shows the format.
The enqueue operation
The enqueue operation inserts an item at the rear of the
queue. The following shows the format.
The dequeue operation
The dequeue operation deletes the item at the front of the
queue. The following shows the format.
The empty operation
The empty operation checks the status of the queue. The
following shows the format.

This operation returns true if the queue is empty and false if


the queue is not empty.
Queue ADT

We define a queue as an ADT as shown below:


Figure shows a segment of an algorithm that applies the
previously defined operations on a queue Q.
Queue applications

•Queues are one of the most common of all data


processing structures.

•They are found in virtually every operating system and


network and in countless other areas.

•For example, queues are used in online business


applications such as
•processing customer requests,
•jobs and orders.

•In a computer system, a queue is needed to process jobs


and for system services such as print spools.
SO2 - Queue implementation
ASSESSMENT
1. In what order the elements of a queue are
accessed
– A. FIFO b. LILO C. LIFO D. FILO
2. The operation for removing an entry from a
queue is traditionally called:
A. delete B. Enqueue C. dequeue D. remove
3. The operation for adding an entry to a Queue is
traditionally called:
A. add B. append C. insert D. Enqueue
SO 3: Array Implementation
ENQUEUE ROUTINE
void enqueue()
{
   if(rear == SIZE - 1)
   {
   printf("Queue is full (overflow)") ;
   getch() ;
   return ;
   }
   rear++ ;
   printf("Enter the element to ENQUEUE : ") ;
   scanf("%d", &arr[rear]) ;
   if(front == -1)
   front++ ;
}
DEQUEUE ROUTINE
void dequeue()
{
   if(front == -1)  
{
printf("Queue is empty (underflow)") ;
   getch() ;
   return ;
    }
   printf("The DEQUEUE element is : %d", arr[front]) ;
   getch() ;
   if(front == rear)
   front = rear = -1 ;
   else
   front++ ;
}
DISPLAY ROUTINE
void display()
{
   if(front == -1)
   {
   printf("Queue is empty (underflow)") ;
   getch() ;
   return ;
   }
   printf(“The elements in queue are :FRONT ->") ;
for(i = front ; i <= rear ; i++)
    printf(" ... %d", arr[i]) ;
    printf(" ... <- REAR") ;
   getch() ;
}
CONTD..
# include <stdio.h>
# include <conio.h>
# define SIZE 10
int arr[SIZE], front = -1, rear = -1, i ;
void enqueue() ;
void dequeue() ;
void display() ;
CONTD…
void main()
{
   int ch ;
   clrscr() ;
   do
   {
   printf("[1].ENQUEUE [2].DEQUEUE [3].Display [4].Exit") ;
   printf("Enter your choice [1-4] : ") ;
   scanf("%d", &ch) ;
CONTD..
switch(ch)
   {
   case 1 :
   enqueue() ;
   break ;
   case 2 :
   dequeue() ;
   break ;
   case 3 :
   display() ;
   break ;
   case 4 :
   break ;
   default :
   printf("Invalid option") ;
getch() ;
   }
   } while(ch != 4) ;
   getch() ;
}
SO4 -Linked List Implementation

• A queue can also be


implemented with a linked list
with both a head and a tail 13
pointer.
15

10

7
null
head_ptr
tail_ptr
Linked List Implementation

• Which end do you think is the


front of the queue? Why?
13

15

10

7
null
head_ptr
tail_ptr
Linked List Implementation

• The head_ptr points to the front


of the list.
• Because it is harder to remove 13 Front
items from the tail of the list.
15

10

7
null
head_ptr
tail_ptr
Rear
LINKED LIST IMPLEMENTATION OF QUEUE

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
Struct qnode
{
Char data;
Qnode *next;
};
Qnode *front=NULL,*rear=NULL,*newnode,*temp;
ENQUEUE ROUTINE
Void enqueue(char data)
{
newnode=(qnode*)malloc(sizeof(qnode));
newnode->data=data;
newnode->next=NULL;
if(front==NULL&&rear==NULL)
{
front=rear=newnode;
}
CONTD..

Else if(front!=NULL && rear!=NULL)


{
rear->next=newnode;
rear=newnode;
}
}
DEQUEUE ROUTINE
Char dequeue()
{
if(front==NULL)
return ‘\0’;
else
{
char ch=front->data;
temp=front;
front=front->next;
if(front==NULL)
` rear=NULL;
free(temp);
return ch;
}
}
DISPLAY ROUTINE
Void display()
{
if(front==NULL)
printf(“The queue has no data\n”);
else
{
temp=front;
While(temp!=NULL)
{
printf(“%c\n”,temp->data);
temp=temp->next;
}
}
}
CONTD..

Void main()
{
enqueue(a);
enqueue(b);
display();
}

You might also like