0% found this document useful (0 votes)
8 views

Linked list

The document discusses linked lists as a flexible data structure compared to arrays, detailing types such as singly, doubly, and circular linked lists, along with their operations like insertion, deletion, and traversal. It also covers dynamic memory allocation in C, including functions like malloc, calloc, free, and realloc, and explains pointers, structures, and their usage in managing linked lists. Key differences between linked lists and arrays are highlighted, emphasizing the advantages of linked lists in terms of memory allocation and efficiency in certain operations.

Uploaded by

Vrushabh Nipane
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)
8 views

Linked list

The document discusses linked lists as a flexible data structure compared to arrays, detailing types such as singly, doubly, and circular linked lists, along with their operations like insertion, deletion, and traversal. It also covers dynamic memory allocation in C, including functions like malloc, calloc, free, and realloc, and explains pointers, structures, and their usage in managing linked lists. Key differences between linked lists and arrays are highlighted, emphasizing the advantages of linked lists in terms of memory allocation and efficiency in certain operations.

Uploaded by

Vrushabh Nipane
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/ 53

Linked Unit 3

list
List as ADT

Concept of linked organization of data against linked list

Singly linked list

Doubly linked list

Circular linked list

LISTS Representation & manipulations of polynomials/sets using


linked lists
Dynamic memory management

Representation of sparse matrix

Addition and transpose of sparse matrix.


Array
Array
Setback of an array
While arrays are useful for grouping
related data

limitation:

• Fixed Size Allocation: Memory for an array is


allocated before program execution.
• Inflexibility: If additional elements need to be stored
at runtime beyond the array’s capacity, it is not
possible without creating a new array with a larger
size.
linked lists provide a more
flexible data structure that
To supports dynamic memory
allocation at runtime.
overcome
this
limitation
This eliminates the need to pre-
allocate memory at compile
time.
Void Pointer
• A void pointer (also called a generic pointer) is a
special type of pointer in C that can point to any data
type.
• Unlike standard pointers (e.g., int * for integers, float * for
floats),
• a void pointer does not have a specific data type
associated with it.
• Why Use a Void Pointer?
• Generalization: It can store addresses of any data type.
• Dynamic Memory Allocation: Functions like malloc(), calloc(),
and realloc() return void *, allowing memory allocation for
different types dynamically.
Dereferencing a Void Pointer
• Since a void pointer does not #include <stdio.h>
have a specific type, the int main() {
compiler cannot determine int x = 100;
the type of data it points to. float y = 50.50;
void *vptr;
• Therefore, explicit vptr = &x;
typecasting is required when printf("\nx = %d",
dereferencing: *((int*)vptr)); // Typecast to
int
vptr = &y;
printf("\ny = %f",
*((float*)vptr)); // Typecast to
float
return 0;
}
Difference
NULL vs.
NULL Pointer vs.
Uninitialized
Void Pointer:
Pointer:
• An uninitialized • A NULL pointer is a
pointer contains a value that represents
garbage value an empty address
(undefined). (NULL or 0).
• A NULL pointer is • A void pointer is a
explicitly assigned pointer data type
NULL (zero memory that can point to any
address). type.
What is a Pointer?
• A pointer is a variable that stores the memory address
of another variable.
int a = 10;
int *ptr = &a; // ptr stores the address of variable 'a’
• What is a Structure?
• A structure (struct) is a user-defined data type that groups
multiple related variables under one name.
struct student {
int roll_no;
char name[20];
};
Pointer to a Structure
• A pointer to a structure stores the address of a
structure variable.

struct student s1;


struct student *ptr = &s1; // ptr points to
structure s1
Pointers with Structures
• Declaring a Structure with a Pointer
struct node {
int data;
struct node *next; //Pointer to another node
};
• 🔹 Accessing Structure Members
• If ptr is a pointer to a structure, we use:
• . (dot operator) when accessing members of a structure
variable.
• -> (arrow operator) when accessing members using a structure
pointer.
ptr->data = 10; // Equivalent to (*ptr).data = 10;
Structure Pointer in C
#include <stdio.h>
struct A {
int var;
};
int main() {
struct A a = {30};
struct A *ptr; // Creating a pointer to the structure
ptr = &a; // Assigning the address of person1 to the pointer

printf("%d", ptr->var); // Accessing structure members using


the pointer
return 0;
}
Pointers and Structure Data Types
#include <stdio.h>
struct student {
char name[10];
int roll_no;
};
int main() {
struct student stud;
struct student *pt = &stud;
Pointers and Structure Data Types
A structure pointer is used to access members of a structure
dynamically
printf("Enter roll number: ");
scanf("%d", &pt->roll_no); // Using arrow operator (->)
printf("Enter name: ");
scanf("%s", pt->name);
printf("\nAccessing student structure data members using
pointer variable:");
printf("\nName: %s Roll Number: %d", pt->name, pt-
>roll_no);
return 0;
}
Pointers and Structure Data Types
(contd.)
Output:
Enter roll number: 21
Enter name: xyz
Accessing student structure data members using pointer
variable:
Name: xyz Roll Number: 21
• Key Takeaways:
• Arrow Operator (->) is used to access structure members
via a pointer.
• Alternative: Instead of pt->name, we can also use
(*pt).name, but parentheses are necessary since . has higher
Dynamic Memory Allocation in C
• in cases where the exact memory requirements are
unknown, dynamic memory allocation (DMA) is
used.
• Why is Dynamic Memory Allocation Needed?
• Efficient Memory Utilization: Avoids allocating excessive
memory.
• Flexibility: Allocates memory at runtime as needed.
• Handling Variable-Sized Data: Useful for linked lists, trees,
graphs, etc.
Memory Management Functions in C
• The C Standard Library provides four functions for dynamic memory
management:

Function Task

malloc() Allocates a single contiguous block of memory.

Allocates multiple blocks of memory and initializes


calloc()
them to zero.

Deallocates memory previously allocated by malloc(),


free()
calloc(), or realloc().

realloc() Resizes an existing allocated memory block.


#include <stdio.h>
#include <stdlib.h>
malloc() Function int main() {
int *ptr;
• Stands for Memory ptr = (int*) malloc(5 *
sizeof(int)); // Allocating memory
Allocation. for 5 integers
• Allocates a single block of
memory of the requested size if (ptr == NULL) {
(in bytes). printf("Memory allocation
failed!\n");
• Returns a void pointer (must return 1;
be typecast). }
• Memory content is uninitialized printf("Memory allocated
(contains garbage values). successfully.\n");
• Syntax: free(ptr); // Deallocate memory
return 0;
ptr = (cast_type*) malloc(byte_size);
}
calloc() Function #include <stdio.h>
#include <stdlib.h>

• Stands for Contiguous int main() {


Allocation. int *ptr;
ptr = (int*) calloc(5,
• Allocates multiple blocks of sizeof(int)); // Allocating memory
memory, initializes them to for 5 integers
zero.
if (ptr == NULL) {
• Syntax: printf("Memory allocation
ptr = (cast_type*) calloc(n, failed!\n");
element_size); return 1;
}
• where:
• n = Number of elements printf("Memory allocated and
• element_size = Size of each initialized to zero.\n");
free(ptr); // Deallocate memory
element return 0;
}
free() Function
• Used to release allocated memory.
• Prevents memory leaks.
• Syntax:
void free(void *ptr);
realloc() Function
• Stands for Reallocation.
• Used to resize previously allocated memory.
• Syntax:
ptr = (cast_type*) realloc(ptr, new_size);
• where:
• ptr = Previously allocated memory
• new_size = New size in bytes
Common Errors in Dynamic Memory Allocation

Error Cause Solution


Forgetting to call Always use
Memory Leak
free() free(ptr);
Dangling Using pointer after Set pointer to NULL
Pointer free() after free()
Double Free Calling free() twice on Ensure pointer is
Error same pointer not already freed
Accessing beyond Always allocate the
Buffer Overflow
allocated memory correct size
Linked List vs. Array

Feature Linked List Array

Non-contiguous (Nodes Contiguous (Stored sequentially


Data Structure
scattered in memory) in memory)

Dynamic (Allocated node by


Memory Allocation Static (Allocated as a whole)
node)

Insertion/Deletion Efficient (O(1) at head) Inefficient (O(n) due to shifting)

Sequential (O(n), requires Random (O(1), direct indexing


Access
traversal) possible)

Flexible (only required memory Fixed (can waste or exceed


Memory Usage
allocated) memory)

Implementation More complex (needs pointers


Simpler (direct indexing)
Complexity & memory management)
• A linked list is a dynamic data structure consisting of
nodes. Each node contains:
Introduction • Data: Stores the actual value (e.g., an integer, character,
or a structure).
to Linked Lists • Link (or Next pointer): Holds the address of the next
node in the list.
Implementation of linked list
• A linked list node contains two parts:
1.INFO (Data field) → Stores the actual information (integer,
character, or any data type).
2.NEXT (Pointer field) → Stores the address of the next node.
• Using a structure (struct), we define a node in C as:
struct node
{
int INFO; // Data part
struct node *NEXT; // Pointer to next node
};
typedef struct node NODE; // Creating an alias for
struct node
Types of Operations in linked list
Creation: This operation is used to create a new linked list.

Insertion: This operation is used to insert a new node at the


specified position, either at the start, end or at the
specified location.
Deletion: This operation is used to delete a node from the start,
end or specified location.

Traversin This operation is used to visit all nodes in the linked list
from either the start or the end of the list.
g:
Searchin This operation is used to find the specific node data is
present in the linked list or not.
g:
Display: This operation is used to print all node data in the linked
list from the start or end of the node.
Insert
Adding the new element

Memory space is reserved for the new node.

The element is stored in the INFO part of the new


node.

The new node is connected to the existing nodes in


the list.
Three possible scenarios
Depending on the location where the new node is to be added

1 2 3
Inserting the Inserting the Inserting the
new element at new element at new element
the beginning of the end of the somewhere at
the list list the middle of the
list
Explanation

1 2
Inserting a new element at Inserting a new element at
the beginning or end the middle of the list
• requires resetting the respective • search operation is required to be
NEXT fields. performed to identify the point of
insertion.
Insertion at the BEGINNING
Condition 1: Condition 2:
Start Start
100
ne INF
NULL INFO
O \0
Step2: Else xt
a. Set NEXT[PTR] =
START
b. Set START = PTR
200

Step1: check whether a


INFO next
list is empty
a. Set START =PTR
b. Set NEXT [PTR] =
NULL
Algorithm to insert an element at the beginning of a linked list.

Step Operation
Step 1 Start
[check whether the list is empty or not ]
If START = NULL, Then /*meaning the list is empty
Step 2 a. set START := PTR , where PTR is the new
node, and
b. set NEXT[PTR] := NULL, /*making it the only
node in the list.

Else
a. set NEXT[PTR] : = START and/*the new node
(PTR) will point to the current first node.
Step 3
b. set Start :=PTR /* updating the head pointer to
the new node.
[end of If structure]
Insertion at the END
Condition 1: Condition 2:
Start Start temp
100
ne 200
INF
NULL INFO
O \0
Step2:xt
Else
a. Set temp:= START
b. Repeat while
next[temp]!=Null
Set temp :=

Step1: check whether a


INFO next NEXT[Temp]
End
list is empty c. Set NEXT[temp]:=
a. Set START =PTR PTR
b. Set NEXT [PTR] = d. Set NEXT[PTR]:=
NULL
Algorithm to insert an element at the END of a linked list.
Step Operation
Step
Start
1
[check whether the list is empty or not ]
Step If START = NULL, Then
2 a. set START := PTR and /* the new node becomes the first node.
b. set NEXT[PTR] := NULL /* as this is the only node in the list.
Else
a. Set a temporary pointer temp := START to traverse the list.
b. Repeat while NEXT[temp]!=Null
Set temp := NEXT[Temp] /* (i.e., move temp to the next node
Step until it reaches the last node).
3 [End of loop]
/*Once the last node is reached */
c. Set NEXT[temp]:= PTR /*linking the last node to the new node.
d. Set NEXT[PTR]:= NULL /*ensuring the new node is the last node.
[end of if]
Step
Stop
Traversing
Start temp

INF
10 200 20 300
O \0
100 200 300

temp temp temp

Step1:
a. Set temp:= START
b. Repeat while next[temp]!=Null
Set temp := NEXT[Temp]
End
c. Exit
Algorithm to insert an element at the END of a linked list.

Step Operation
Step
Start
1
a. Set temp:= START
Step b. Repeat while next[temp]!=Null
2 Set temp := NEXT[Temp]
End of while
Step
Stop
3
Insertion at some specific
position
1: Searching2: Insertion
requires two operations
Start

NULL

Step1: check whether a


INFO next
list is empty
a. Set START =PTR
b. Set NEXT [PTR] =
NULL
Insertion at some specific
position
Start temp

10 200 20 300 30 \0
100 200 300

temp temp

Item = 20 21 300
500

PTR
Algorithm to insert an element at the END of a linked list.
Step Operation
[check whether the list is empty or not ]
If START = NULL, Then
Step 1
a. set START := PTR and
b. set NEXT[PTR] := NULL
Else
a. Set temp := Start
b. Set item := [Read From User]
c. Repeat while NEXT[temp] != NULL
If INFO[temp] = item, then
set NEXT[PTR] :=NEXT[temp]
Step 2 set NEXT[temp]:= PTR
Break
Else
set temp := NEXT[Temp
[end of If]
[End of Loop]

Step 3 Stop
C Program for various Operations in Linked List
#include<stdio.h>
#include<stdlib.h>

//Create NODE Structure


struct node
{
int info;
struct node *next;
} typedef node;
node *start;

//Declaring function prototypes. Basic operations


void insertion();
void deletion();
C Program for various Operations in Linked List
void main()
{
int ch;
do
{
printf("\n*****\t\t\t SINGLY LINKED LIST OPERATIONS \t\t\
t*****");
printf("\n---------------------------------------------");
printf("\n\n1. Insertion");
printf("\n2. Deletion");
printf("\n3. Traverse");
printf("\n4. Exit");
printf("\n---------------------------------------------");
printf("\n\nEnter your choice ==>> ");
scanf("%d", &ch);
C Program for various Operations in Linked List
switch(ch)
{
case 1:
insertion();
break;
case 2:
//deletion();
break;
case 3:
traverse();
break;
}
} while (ch!=4);
C Program for various Operations in Linked List
//Defining Insertion Function
void insertion()
{
int ch;
int item;
node *ptr, *temp;
do
{
printf("\n---------------------------------------------");
printf("\n\n1. Insertion @ Begining");
printf("\n2. Insertion @ End");
printf("\n3. Insertion @ Some Specific Point");
printf("\n4. Exit");
printf("\n---------------------------------------------");
printf("\n\nEnter your choice ==>> ");
scanf("%d", &ch);
C Program for various Operations in Linked List
switch(ch)
{
// Algorithm for insertion at the beginning of linked list
case 1:
ptr = (node *)malloc(sizeof(node));
printf("\nEnter the information of new node ==>> ");
scanf("%d",&ptr->info);
//Algorithm Starts
if(start==NULL)
{
start = ptr;
ptr->next = NULL;
}
C Program for various Operations in Linked List
else{
ptr->next = start;
start = ptr;
}
break;
//Algorithm Ends
C Program for various Operations in Linked List
// Algorithm for insertion at the end of linked list
case 2:
ptr = (node *)malloc(sizeof(node));
printf("\nEnter the information of new node
==>> ");
scanf("%d",&ptr->info);
//Algorithm Starts
if(start==NULL)
{
start = ptr;
ptr->next = NULL;
}
C Program for various Operations in Linked List
else
{
temp= start;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next=ptr;
ptr->next=NULL;
}
break;
//Algorithm Ends
C Program for various Operations in Linked List
// Algorithm for insertion at the any specific position of
linked list
case 3:
ptr = (node *)malloc(sizeof(node));
printf("\nEnter the information of new node
==>>
");
scanf("%d",&ptr->info);
//Algorithm Starts
if(start==NULL)
{
start = ptr;
ptr->next = NULL;
}
C Program for various Operations in
Linked List
else
{
temp = start;
printf("enter the item key:");
scanf("%d",&item);
while(temp->next!=NULL)
{
if(temp->info ==item)
{
ptr->next=temp->next;
temp->next=ptr;
break;
}
C Program for various Operations in Linked
List
else
{
temp= temp->next;
}
}

}
break;
//Algorithm Ends

You might also like