0% found this document useful (0 votes)
24 views55 pages

Unit 2 Linked List

Uploaded by

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

Unit 2 Linked List

Uploaded by

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

Dynamic Memory Allocation

Dr. Jyoti Srivastava


Dynamic Memory Allocation in C
• An array is a collection of fixed number of values of a
single type.

• We need to declare the size of an array before we use it.

• Sometimes, the size of array you declared may be


insufficient.

• To solve this issue, we can allocate memory manually


during run-time. This is known as dynamic memory
allocation in C programming.
Dynamic Memory Allocation in C
There are 4 library functions defined under <stdlib.h> for
dynamic memory allocation in C programming.

 malloc()
 calloc()
 realloc()
 free()
malloc()
• The name "malloc" stands for memory allocation.

• The malloc() function reserves a block of memory of the specified number


of bytes. And, it returns a pointer of type void which can be casted into
pointer of any form.
Syntax of malloc()
ptr = (cast-type*) malloc(byte-size)
Example:
ptr = (int*) malloc(100 * sizeof(int));
• Considering the size of int is 4 bytes, this statement allocates 400 bytes of
memory. And, the pointer ptr holds the address of the first byte in the
allocated memory.

• However, if the space is insufficient, allocation fails and returns a


NULL pointer.
calloc()
• The name "calloc" stands for contiguous allocation.

• The malloc() function allocates a single block of memory. Whereas,


calloc() allocates multiple blocks of memory and initializes them to
zero.

Syntax of calloc()
ptr = (cast-type*)calloc(n, element-size);

Example:
ptr = (float*) calloc(25, sizeof(float));

• This statement allocates contiguous space in memory for 25 elements


each with the size of float.
free()
Dynamically allocated memory created with either calloc() or
malloc() doesn't get freed on their own. You must explicitly use
free() to release the space.

Syntax of free()
free(ptr);

This statement frees the space allocated in the memory pointed by


ptr.
realloc()
If the dynamically allocated memory is insufficient or more than
required, you can change the size of previously allocated memory
using realloc() function

Syntax of realloc()
ptr = realloc(ptr, x);

Here, ptr is reallocated with new size x.

ptr = (int*) malloc(100 * sizeof(int));


ptr = realloc(ptr, 50 * sizeof(int));
Or
ptr = realloc(ptr, 1000 * sizeof(int));
Linear Data Structure:
Linked List
Introduction
• Consisting of a group of nodes which together
represent a sequence.

• Under the simplest form, each node is


composed of a datum and a reference (in other
words, a link) to the next node in the sequence.

• This structure allows for efficient insertion or


removal of elements from any position in the
sequence.
Introduction

A linked list whose nodes contain two fields:

• an integer value and a link to the next node.

• The last node is linked to a terminator (NULL


pointer) used to signify the end of the list.
Advantage

•They are dynamic in nature which allocates


the memory when required.

•Provides quick insert and delete operations.

•Stacks and queues can be easily executed.


Disadvantage
•The memory is wasted as pointers require extra
memory for storage.

•Slow search operations

•No element can be accessed randomly; it has to


access each node sequentially.

•Reverse Traversing is difficult in linked list.


Memory Representation

Start Data Next After traversal,


1 1 H 4 we get HELLO within
2 this linked list
3
4 E 7
5
6
7 L 8
8 L 10
9
10 O -1
Linked List vs. Arrays
• The size of the arrays is fixed: So we must know the upper
limit on the number of elements in advance.

• Inserting a new element in an array of elements is expensive,


because room has to be created for the new elements. To
create room, existing elements have to shift.

• Random access is not allowed in Link List. We have to access


elements sequentially starting from the first node. So we
cannot do binary search with linked lists.

• Extra memory space for a pointer is required with each


element of the list.
Applications of Linked Lists

• Linked lists are used to implement stacks, queues,


graphs, etc.

• Linked lists let you insert elements at the beginning


and end of the list.

• In Linked Lists we don’t need to know the size in


advance.
Memory allocation & de-allocation

• Operating system bears the responsibility to change


the status of the memory occupied to available and
vice versa without intervention from user.

• Consider, we have a pointer AVAIL which stores the


address of the first free address. (Free Pool)

• AVAIL will be useful to store new value.


Memory allocation & de-allocation

Start Data Next Start Data Next


1 1 H 4 1 1 H 4
AVAIL 2 2 W -1
3 AVAIL 3
4 E 7 4 E 7
5 5
6 6
7 L 8 7 L 8
8 L 10 8 L 10
9 9
10 O -1 10 O 2
Types of Linked Lists
• Singly Linked List

• Doubly Linked List

• Circular Linked List


Singly Linked-List

• Simplest type of linked list in which every node


contains data and pointer.

• A singly linked list allows traversal of data only in


one way.
Algorithm for traversing a linked list
Step 1: [INITIALIZE] SET PTR = START
Step 2: Repeat Steps 3 and 4 while PTR != NULL
Step 3: Apply Process to PTR -> DATA
Step 4: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 5: EXIT
Algorithm to print each node of the linked list

Step 1: [INITIALIZE] SET PTR = START


Step 2: Repeat Steps 3 and 4 while PTR != NULL
Step 3: Write PTR -> DATA
Step 4: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 5: EXIT
Algorithm to print the number of nodes
in the linked list
Step 1: [INITIALIZE] SET Count = 0

Step 2: [INITIALIZE] SET PTR = START

Step 3: Repeat Steps 4 and 5 while PTR != NULL

Step 4: SET Count = Count + 1

Step 5: SET PTR = PTR -> NEXT


[END OF LOOP]
Step 6: EXIT
Searching an unsorted linked list

• Find VAL = 4
1 7 3 4 5 2 X

PTR
(Here, PTR -> DATA != 4, so move to next node)

1 7 3 4 5 2 X

1 7 3 4 5 2 X

1 7 3 4 5 2 X

PTR
(Here, PTR -> DATA = 4, so POS = PTR)
Searching an unsorted Linked List

Step 1: [INITIALIZE] SET PTR = START


Step 2: Repeat Steps 3 while PTR != NULL
Step 3: IF VAL = PTR -> DATA
SET POS = PTR
Go To Step 5
ELSE
SET PTR = PTR -> NEXT
[END OF IF]
[END OF LOOP]
Step 4: SET POS = NULL
Step 5: EXIT
Inserting a new node in Linked List

Case 1: New node is inserted at the beginning

Case 2: New node is inserted at the end

Case 3: New node is inserted after a given node

Case 4: New node is inserted before a given node

Case 5: New node is inserted in a sorted linked list


Case 1: New node is inserted at the beginning

1 7 3 4 5 2 X

START
9

9 1 7 3 4 5 2 X

START

9 1 7 3 4 5 2 X

START
Case 1: New node is inserted at the beginning

Step 1: IF AVAIL = NULL then


Write OVERFLOW
GO TO Step 7
[END OF IF]
Step 2: SET New_Node = AVAIL
Step 3: SET AVAIL = AVAIL -> NEXT
Step 4: SET New_Node -> DATA = VAL
Step 5: SET New_Node -> NEXT = START
Step 6: SET START = New_Node
Step 7: EXIT
Case 2: New node is inserted at the end

1 7 3 4 5 2 X

START

9 X

1 7 3 4 5 2 9 X

START
Case 2: New node is inserted at the end
Step 1: IF AVAIL = NULL then
Write OVERFLOW
GO TO Step 11
[END OF IF]
Step 2: SET New_Node = AVAIL
Step 3: SET AVAIL = AVAIL -> NEXT
Step 4: SET New_Node -> DATA = VAL
Step 5: SET New_Node -> NEXT = NULL
Step 6: IF START = NULL
START = New_Node
GO TO Step 11
[END OF IF]
Step 7: SET PTR = START
Step 8: Repeat Step 9 while PTR -> NEXT != NULL
Step 9: SET PTR = PTR -> NEXT
[END of LOOP]
Step 10: SET PTR -> NEXT = New_Node
Step 11: EXIT
Deleting node from LL
Case 1: First node is deleted
Case 2: Last node is deleted
Case 3: Node after a given node is deleted
Case 4: Node is deleted from a sorted linked list
Case 1: First node is deleted

1 7 3 4 5 2 X

START

SET START = START -> NEXT

7 3 4 5 2 X

START
Case 1: First node is deleted
Step 1: IF START = NULL then
Write UNDERFLOW
GO TO Step 5
[END OF IF]
Step 2: SET PTR = START
Step 3: SET START = START -> NEXT
Step 4: FREE PTR
Step 5: EXIT
Case 2: Last node is deleted

1 7 3 4 5 2 X

START

1 7 3 4 5 X

START
Case 2: Last node is deleted
Step 1: IF START = NULL then
Write UNDERFLOW
GO TO Step 8
[END OF IF]
Step 2: SET PTR = START
Step 3: Repeat Step 4 and 5 while PTR -> NEXT != NULL
Step 4: SET PREPTR = PTR
Step 5: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 6: IF PTR = START then
START = NULL
ELSE
SET PREPTR -> NEXT = NULL
[END OF IF]
Step 7: FREE PTR
Step 8: EXIT
Circular Linked List

• In the last node of a list, the link field often contains


a null reference, a special value used to indicate the
lack of further nodes.

• A less common convention is to make it point to the


first node of the list; in that case the list is said to
be circular or circularly linked.
Circular Linked List

Advantages
1. In linear linked list it is not possible to go to previous
node but within Circular LL possible.

2. It saves time when we have to go to the first node from


the last node. It can be done in single step because there
is no need to traverse in between nodes. But in double
linked list, we will have to go through in between nodes.
Circular Linked List

Disadvantages
1. If proper care is not taken, then the problem of
infinite loop can occur.

2. If we at a node and go back to the previous node,


then we can not do it in single step. Instead we
have to complete the entire circle by going
through the in between nodes and then we will
reach the required node.
Insert new node in Circular LL
Case 1: New node is inserted at the beginning
Case 2: New node is inserted at the end
Delete node from Circular LL
Case 1: Node is deleted at the beginning
Case 2: Node is deleted at the end
Doubly Linked List

• In Doubly-linked list each node has two links: one


points to previous node and one points to next node.

• The previous link of first node in the list points to a


Null and the next link of last node points to Null.
Advantages

• Traversal in either direction becomes convenient.

• Reduces time requirement for the program


execution.

• The doubly linked lists can be used to represent


other data-structure. The hierarchical structure of the
tree can be easily represented using a doubly linked
list. Graphs can be represented using doubly linked
list.
Disadvantages
• Each node requires extra space for storing the
additional pointer.

• While manipulating the lists, extra care should be


taken to manipulate both links.
Representation

struct node {
struct node *prev;
int info ;
struct node *next;
};
Inserting a new node in DLL

Case 1: New node is inserted at the beginning


Case 2: New node is inserted at the end
Deleting a node from DLL

Case 1: Node is deleted at the beginning


Case 2: Node is deleted at the end
Circular Doubly Linked List

• A doubly linked list is where each element has pointers to


both the next element and the prior element.

• A circular doubly linked list is where the last element points


back to the first element, and first element points to the last.
Inserting a new node in CDLL
Case 1: New node is inserted at the beginning
Case 2: New node is inserted at the end
Delete node from CDLL
Case 1: Node is deleted at the beginning
Case 2: Node is deleted at the end
Polynomials
Representing Polynomials As Singly Linked Lists
• The manipulation of symbolic polynomials, has a classic example
of list processing.
• In general, we want to represent the polynomial:
A( x )  am1 x em 1      a0 x e0
• Where the ai are nonzero coefficients and the ei are
nonnegative integer exponents such that
em-1 > em-2 > … > e1 > e0 ≧ 0 .
• We will represent each term as a node containing coefficient and
exponent fields, as well as a pointer to the next term.
Polynomials Representation
• Assuming that the coefficients are integers, the type declarations
are:
struct poly_node {
int coef;
int exp;
struct poly_node * poly_pointer;
};

• Draw poly_nodes as:


coef exp link

• With linked lists, it is much easier to perform operations on


polynomials such as adding and deleting.
Polynomials Representation

a.first 3 14 2 8 1 0 X
a  3 x14  2 x 8  1

b.first 8 14 -3 10 10 6 X

b  8 x14  3x10  10 x 6
Operating On Polynomials
• Adding Polynomials
• To add two polynomials, we examine their terms pointed
to by p and q.
• If the exponents of the two terms are equal
1. add the two coefficients
2. create a new term for the result.
• If the exponent of the current term in p is less than q
1. create a duplicate term of q
2. attach this term to the result
3. advance the pointer to the next term in q.
• We take a similar action on a if p->exp > q->exp.
Operating On Polynomials
• E.g., adding two polynomials a and b

a.first 3 14 2 8 1 0 X
p

b.first 8 14 -3 10 10 6 X

q
c.first 11 14 X
(i) p->exp == q->exp
Operating On Polynomials

a.first 3 14 2 8 1 0 X

b.first 8 14 -3 10 10 6 X

q
c.first 11 14 -3 10 X

(ii) p->exp < q->exp


Operating On Polynomials

a.first 3 14 2 8 1 0 X

b.first 8 14 -3 10 10 6 X

q
c.first 11 14 -3 10 2 8 X

(iii) p->exp > q->exp


In the same way complete the addition of these two polynomials.

You might also like