0% found this document useful (0 votes)
22 views83 pages

UNIT 4 Link List

The document discusses linked lists. It provides an introduction to linked lists, describing them as dynamic data structures where each node contains a data field and pointer to the next node. It covers the basic operations on linked lists like creation, traversal, search, insert, delete, and different types of linked lists like singly linked, doubly linked, circular linked lists.

Uploaded by

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

UNIT 4 Link List

The document discusses linked lists. It provides an introduction to linked lists, describing them as dynamic data structures where each node contains a data field and pointer to the next node. It covers the basic operations on linked lists like creation, traversal, search, insert, delete, and different types of linked lists like singly linked, doubly linked, circular linked lists.

Uploaded by

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

Linked List

Spring 2012 Programming and Data Structure 1


Syllabus
• Introduction to Static and Dynamic Memory
Allocation,
• Linked List: Introduction, of Linked Lists,
Realization of linked list using dynamic
memory management,
• Operations, Linked List as ADT, Types of
Linked List: singly linked, linear and Circular
Linked Lists, Doubly Linked List, Doubly
Circular Linked List, Primitive Operations on
Linked List-Create, Traverse, Search, Insert,
Delete, Sort, Concatenate. Polynomial
Manipulations-Polynomial addition.
Difference between static and dynamic memory
allocation
.No Static Memory Allocation Dynamic Memory Allocation
1 When the allocation of memory When the memory allocation is
performs at the compile time, done at the execution or run
then it is known as static time, then it is called dynamic
memory. memory allocation.

2 The memory is allocated at the The memory is allocated at the


compile time. runtime.

3 In static memory allocation, In dynamic memory allocation,


while executing a program, the while executing a program, the
memory cannot be changed. memory can be changed.

4 Static memory allocation is Dynamic memory allocation is


preferred in an array. preferred in the linked list.
5 It saves running time as it is It is slower than static
fast. memory allocation.

6 Static memory allocation Dynamic memory allocation


allots memory from the allots memory from the
stack. heap.

7 Once the memory is Here, the memory can be


allotted, it will remain from alloted at any time in the
the beginning to end of the program.
program.

8 Static memory allocation is Dynamic memory allocation


less efficient as compared is more efficient as
to Dynamic memory compared to the Static
allocation. memory allocation.
Link list
• Introduction to link list
A Linked List is a linear data structure which looks like a
chain of nodes, where each node is a different element.
Unlike Arrays, Linked List elements are not stored at a
contiguous location.
• A linked list is a linear data structure that
stores a collection of data elements
dynamically.
• Nodes represent those data elements, and
links or pointers connect each node.
• Each node consists of two fields, the
information stored in a linked list and a
pointer that stores the address of its next
node.
Representation of a Linked List

• This representation of a linked list depicts that


each node consists of two fields.
• The first field consists of data, and the second
field consists of pointers that point to another
node.
Creation of Node and Declaration of Linked
Lists
• struct node

• {
• int data;

• struct node * next;

• };

• struct node * n;

• n=(struct node*)malloc(sizeof(struct node*));


• Or (in C++)
• n= new node(); // new keyword is used to create dynamic memory
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

Spring 2012 Programming and Data Structure 9


• 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 10


Illustration: Insertion
A B C

Item to be
tmp X inserted

A B C

curr
X

Spring 2012 Programming and Data Structure 11


Illustration: Deletion
Item to be deleted

A B C

tmp
curr

A B C

Spring 2012 Programming and Data Structure 12


Spring 2012 Programming and Data Structure 13
Example
Assume that the linked list has elements:
20 30 40 NULL
If we insert 100, it will be added at the
beginning of a linked list.
After insertion, the new linked list will be
100 20 30 40 NULL

Spring 2012 Programming and Data Structure 14


Algorithm

1. Declare a head pointer and make it as


NULL.
2. Create a new node with the given data.
3. Make the new node points to the head
node.
4. Finally, make the new node as the head
node.

Spring 2012 Programming and Data Structure 15


#include <iostream>
using namespace std;

//Creating Node Structure


struct Node
{
int data;
Node *link;
};
//creating head pointer and equating to NULL
Node *head=NULL;

//Function to insert at the beginning of linked list


void insertBeg (int d)
{
Node *ptr = new Node();
ptr->data=d;
ptr->link=head;
head=ptr;
}
Spring 2012 Programming and Data Structure 16
void insertEnd (int d)
{
Node *ptr = new Node();
ptr->data=d;
ptr->link=NULL;

//If list is empty


if(head==NULL)
head=ptr;
//else list is not empty
else
{
Node *temp = head;
while(temp->link != NULL)
{
temp=temp->link;
Spring 2012
} temp->link=ptr; }}
Programming and Data Structure 17
//Function to display linked list
void dispLink()
{
Node *temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->link;
}
cout<<"\n";
}
//Main Function
int main()
{
insertBeg(2);
insertBeg(1); insertEnd(3);
dispLink(); return 0;Programming and Data Structure
Spring 2012 18
Node Deleted at beginning
1.void begdelete()
2. {
3. struct node *ptr;
4. if(head == NULL)
5. {
6. printf("\nList is empty");
7. }
8. else
9. {
10. ptr = head;
11. head = ptr->next;
12. free(ptr);
13. printf("\n Node deleted from the begining ...");

Spring 2012 Programming and Data Structure 19


//Function to delete node at the end
void deleteEnd()
{
Node *ptr;

//if list is empty.


if(head==NULL)
cout<<"EMPTY LIST\n";
//if list has only one node.
if(head->link==NULL)
{
ptr=head;
head=NULL;
free(ptr);
}

Spring 2012 Programming and Data Structure 20


//Traversing the list.
else
{ Node *prev;
ptr=head;
while(ptr->link!=NULL)
{
prev=ptr;
ptr=ptr->link;
}
prev->link=NULL;
free(ptr);
}

}
Spring 2012 Programming and Data Structure 21
Circular Link list
Circular Linked List is a variation of
Linked list in which the first element
points to the last element and the last
element points to the first element.

Spring 2012 Programming and Data Structure 22


Basic Operations

Following are the important operations


supported by a circular list.

•insert − Inserts an element at the start


of the list.
•delete − Deletes an element from the
start of the list.
•display − Displays the list.

Spring 2012 Programming and Data Structure 23


Algorithm to insert element at
beg/start in CLL
1. START
2. Check if the list is empty
3. If the list is empty, add the node and
point the head to this node
4. If the list is not empty, link the existing
head as the next node to the new node.
5. Make the new node as the new head.
6. END

Spring 2012 Programming and Data Structure 24


Spring 2012 Programming and Data Structure 25
Spring 2012 Programming and Data Structure 26
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 27


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 28


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)


head
• One we have discussed so far.

A B C

Spring 2012 Programming and Data Structure 29


– Circular linked list
• The pointer from the last element in the list points back
to the first element.
head

A B C

Spring 2012 Programming and Data Structure 30


– 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 the list, head and tail. tail

A B C

Spring 2012 Programming and Data Structure 31


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 32


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 33


Conceptual Idea

Insert
List
implementation
Delete and the
related functions
Traverse

Spring 2012 Programming and Data Structure 34


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 35


Creating a List

Spring 2012 Programming and Data Structure 36


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));
head
roll

name next
age

Spring 2012 Programming and Data Structure 37


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

Spring 2012 Programming and Data Structure 38


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 39


• To be called from main() function as:

node *head;
………
head = create_list();

Spring 2012 Programming and Data Structure 40


Traversing the List

Spring 2012 Programming and Data Structure 41


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 42


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 43


• To be called from main() function as:

node *head;
………
display (head);

Spring 2012 Programming and Data Structure 44


Inserting a Node in a List

Spring 2012 Programming and Data Structure 45


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 46


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 47


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 48


else
{
while ((p != NULL) && (p->roll != rno))

{
q = p;
p = p->next;
} The pointers
q and p
if (p == NULL) /* At the end */ always point
{ to consecutive
q->next = new; nodes.
new->next = NULL;
}
else if (p->roll == rno)
/* In the middle */
{
q->next = new;
new->next = p;
}
}
}
Spring 2012 Programming and Data Structure 49
• To be called from main() function as:

node *head;
………
insert (&head);

Spring 2012 Programming and Data Structure 50


Deleting a node from the list

Spring 2012 Programming and Data Structure 51


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 52


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 53


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);
}
}
}

Spring 2012 Programming and Data Structure 54


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 55


A First-in First-out (FIFO) List
In Out

B A
C B A

Also called a QUEUE

Spring 2012 Programming and Data Structure 56


A Last-in First-out (LIFO) List
In Out

C B A B C

Also called a
STACK

Spring 2012 Programming and Data Structure 57


Abstract Data Types

Spring 2012 Programming and Data Structure 58


Example 1 :: Complex numbers
struct cplx {
float re; Structure
float im;
definition
}
typedef struct cplx complex;

complex *add (complex a, complex b);


complex *sub (complex a, complex b);
complex *mul (complex a, complex b); Function
complex *div (complex a, complex b);
prototypes
complex *read();
void print (complex a);

Spring 2012 Programming and Data Structure 59


add

sub

mul Complex
Number
div

read

print
Spring 2012 Programming and Data Structure 60
Example 2 :: Set manipulation
struct node {
int element; Structure
struct node *next;
definition
}
typedef struct node set;

set *union (set a, set b);


set *intersect (set a, set b);
set *minus (set a, set b); Function
void insert (set a, int x); prototypes
void delete (set a, int x);
int size (set a);

Spring 2012 Programming and Data Structure 61


union

intersect

minus
Set
insert

delete

size
Spring 2012 Programming and Data Structure 62
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 63


push

pop

create
STACK
isempty

isfull

Spring 2012 Programming and Data Structure 64


Contd.
• We shall look into two different ways of
implementing stack:
– Using arrays
– Using linked list

Spring 2012 Programming and Data Structure 65


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 66


enqueue

dequeue

create
QUEUE
isempty

size

Spring 2012 Programming and Data Structure 67


Stack Implementations: Using Array and
Linked List

Spring 2012 Programming and Data Structure 68


STACK USING ARRAY

PUSH

to
p
to
p

Spring 2012 Programming and Data Structure 69


STACK USING ARRAY

POP

to
p
to
p

Spring 2012 Programming and Data Structure 70


Stack: Linked List Structure

PUSH OPERATION

top

Spring 2012 Programming and Data Structure 71


Stack: Linked List Structure

POP OPERATION

top

Spring 2012 Programming and Data Structure 72


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 74


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 LINKED LIST

Spring 2012 Programming and Data Structure 75


Stack Creation
void create (stack *s) void create (stack **top)
{ {
s->top = -1; *top = NULL;

/* s->top points to /* top points to NULL,


last element indicating empty
pushed in; stack */
initially -1 */ }
}
LINKED LIST
ARRAY

Spring 2012 Programming and Data Structure 76


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;
}
}

ARRAY

Spring 2012 Programming and Data Structure 77


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

Spring 2012 Programming and Data Structure 78


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

Spring 2012 Programming and Data Structure 79


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;
}
}

Spring 2012 Programming and Data Structure 80


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);
} }

ARRAY LINKED LIST

Spring 2012 Programming and Data Structure 81


Checking for stack full
int isfull (stack *s) • Not required for linked list
{ implementation.
if (s->top == • In the push() function, we
(MAXSIZE–1)) can check the return value of
malloc().
return 1; – If -1, then memory cannot be
else allocated.
return (0);
}
ARRAY LINKED LIST

Spring 2012 Programming and Data Structure 82


Example main function :: array
#include <stdio.h> push(&A,30);
#define MAXSIZE 100 push(&B,100); push(&B,5);
struct lifo printf (“%d %d”, pop(&A),
{ pop(&B));
int st[MAXSIZE];
int top; push (&A, pop(&B));
}; if (isempty(&B))
typedef struct lifo stack; printf (“\n B is empty”);
main() }
{
stack A, B;
create(&A); create(&B);
push(&A,10);
push(&A,20);

Spring 2012 Programming and Data Structure 83


Example main function :: linked list
#include <stdio.h> push(&A,30);
struct lifo push(&B,100);
{ push(&B,5);
int value;
printf (“%d %d”,
struct lifo *next;
pop(&A), pop(&B));
};
typedef struct lifo stack; push (&A, pop(&B));
main() if (isempty(B))
{ printf (“\n B is
stack *A, *B; empty”);
create(&A); create(&B); }
push(&A,10);
push(&A,20);

Spring 2012 Programming and Data Structure 84

You might also like