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

4.linked List

This document discusses linked lists as a data structure. It begins by defining key terms like nodes, linked lists, and pointers. It then compares arrays and linked lists, noting advantages and disadvantages of each. Specific linked list operations like creation, insertion, deletion and traversal are covered. The document provides examples of how to implement a single linked list in C using structures and dynamic memory allocation functions like malloc(). It also discusses traversing, searching and counting nodes in a linked list.

Uploaded by

Lakruwan Kasun
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)
29 views

4.linked List

This document discusses linked lists as a data structure. It begins by defining key terms like nodes, linked lists, and pointers. It then compares arrays and linked lists, noting advantages and disadvantages of each. Specific linked list operations like creation, insertion, deletion and traversal are covered. The document provides examples of how to implement a single linked list in C using structures and dynamic memory allocation functions like malloc(). It also discusses traversing, searching and counting nodes in a linked list.

Uploaded by

Lakruwan Kasun
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/ 68

DATA STRUCTURES AND

ALGORITHMS-1 (CS)
Prof. M.G.Noel A.S Fernando
Professor in Computer Science
Head, Dept. of Information Systems Engineering, Head, External Degree &
Extension programmes , UCSC
Lecture 4
List Data Structures

Arrays
Stacks
Queues

Linked(singly) list
Doubly linked List
Circular Linked List
Linked list based Stacks
and Queues
Array based and Linked List
structures
• The array is a linear collection of data
elements in which the elements are stored
in consecutive memory locations.
Array based and Linked List structures
• The array is a linear collection of data elements
in which the elements are stored in consecutive
memory locations.

• While declaring arrays, we have to specify the


size of the array, which will restrict the number of
elements that the array can store.
• For example, if we declare an array as int
marks[10], then the array can store a maximum
of 10 data elements but not more than that.
LINKED LISTS
Example

• Cells (nodes) like these are connected in various ways


to build a data structure.
Linked List as a Data Structure
Linked lists
What is a Linked List?
What is linked list ?(Continued)
• Think of each element in a linked list as
being an individual piece in a child's pop
chain. To form a chain, insert the
connector into the back of the next piece
Introducing Linked Lists (continued)

• Inserting a new piece into the chain


involves merely breaking a
connection and reconnecting the
chain at both ends of the new piece.
What is linked list(continued)
• Removal of a piece from anywhere in
the chain requires breaking its two
connections, removing the piece,
and then reconnecting the chain.
Details definition of Linked List
Array Vs Linked Lists

Arrays Linked List

Fixed Size Dynamic Size

Insertions and deletions are inefficient :elements are Insertions and deletions are efficient :no shifting
usually shifted
Random access : efficient indexing No random access

No memory wastage, if array is full or almost full. Since memory is dynamically allocated (according to our
Otherwise, memory wastage requirement) there is no waste of memory
Sequential access is faster [Reason : Elements in Sequential access is not faster [Reason : Elements not in
contiguous memory locations] contiguous memory locations]
Basic Terminologies
• A linked list, is a linear collection of data
elements.
• These data elements are called nodes.
• It acts as a building block to implement data
structures such as stacks, queues, and their
variations.
• A linked list can be perceived as a train or a
sequence of nodes in which each node contains
one or more data fields and a pointer to the next
node.
Simple linked list

Linked lists contain a pointer variable START that stores the address of the first node
in the list.

We can traverse the entire list using START which contains the address of the first
node;
If START = NULL, then the linked list is empty and contains no nodes
In C, we can implement a linked list
using the following code:

Note :This is denoted graphically a self loop


Dynamic memory allocation
• Dynamic memory = memory allocated at run-time.
• Static memory = memory allocated at compile-time.
• Programming languages like C and Pascal provide
libraries for managing dynamic memory.
• This memory is allocated from a special area called
heap.
• The heap is managed by a special language component
that implements functions like new and dispose in
Pascal or malloc(), calloc() and free() in C.
How a linked list is maintained in the
memory
• The node which has two fields, DATA and
NEXT.
• DATA will store in the information part and
NEXT will store the address of the next node
in sequence.
• the variable START is used to store the address
of the first node.
• Here, in this example, START = 1, so the first
data is stored at address 1, which is H.
How a linked list is maintained in the
memory

At the end, NEXT entry contains


–1 or NULL
Two different linked lists are
simultaneously maintained in the
memory
Homework
• Discuss the advantages, disadvantages,
similarities and differences of Linked Lists
versus Arrays.
• You may use the following table to answer
the question
Sample Students’ linked list
Memory management in C
• The C programming language provides several
functions for memory allocation and
management.
• These functions can be found in
the <stdlib.h> header file.
• Although C inherently does not have any
techniques to allocate memory dynamically.
There are 4 library functions defined under
<stdlib.h> for dynamic memory allocation.
Memory management functions in C
C malloc()

• The name malloc stands for “memory allocation”


• The function malloc() reserves a block of memory of
specified size and return a pointer of type void which
can be casted into pointer of any form.
• Syntax
Ptr = (cast-type*) malloc (byte-size)
• Here, ptr is pointer of cast-type. The malloc() function
returns a pointer to an area of memory with size of
byte size.
• If the space is insufficient, allocation fails and returns
NULL pointer.
C malloc()

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


• This statement will allocate either 200 or 400
according to size int 2 or 4 bytes respectively and
the pointer points to the first byte of the
memory.
C - calloc() – stands for “contiguous
allocation”
• Syntax of calloc()
Ptr = (cast-type*) calloc (n,element-size);
• This statement will allocate contiguous space in
memory for an array of n elements.
• Example
• Ptr=(float*)calloc(25,sizeof(float));
• This statement allocates contiguous space in
memory for an array of 25 elements each of
size of float, i.e, 4 bytes
C - free()

• Dynamically allocated memory created with


either calloc() or malloc() doesn't get freed on
its own. You must explicitly use free() to
release the space.
• syntax of free()
• Free(ptr);
• This statement frees (release) the space
allocated in the memory in the memory
pointed ptr.
Single Linked List
• A linked list allocates space for each element
separately in its own block of memory called a "node".
• The list gets an overall structure by using pointers to
connect all its nodes together like the links in a chain.
Each node contains two fields; a "data" field to store
whatever element, and a "next" field which is a pointer
used to link to the next node.
• Each node is allocated in the heap using malloc(), so
the node memory continues to exist until it is explicitly
de-allocated using free().
• The front of the list is a pointer to the “start” node.
Example :A single linked list
Implementation of Single Linked List
• Before writing the code to build the above list, we
need to create a start node, used to create and
access other nodes in the linked list.
• Structure definition, single link node and empty
list:
• Creating a structure with one data item and a
next pointer, which will be pointing to next node
of the list.
• This is called as self-referential structure.
• Initialize the start pointer to be NULL.
Structure definition, single link node
and empty list
The basic operations in a single linked
list are:
• Creation.
• Insertion.
• Deletion.
• Traversing
Creating a node for Single Linked List:
• Creating a singly linked list starts with creating a node.
• Sufficient memory has to be allocated for creating a
node.
• The information is stored in the memory, allocated by
using the malloc() function.
• The function getnode(), is used for creating a node,
after allocating memory for the structure of type node,
the information for the item (i.e., data) has to be read
from the user, set next field to NULL and finally returns
the address of the node. The following Figure
illustrates the creation of a node for single linked list.
The following figure illustrates the
creation of a node for single linked list.

newnode with a value of 10


Creating a Singly Linked List with ‘n’
number of nodes:
• The following steps are to be followed to
create ‘n’ number of nodes:
4 items in a single linked list stored at
different locations in memory.
The function createlist(), is used to create ‘n’ number of nodes:
Traversing a Linked List
• Traversing a linked list means accessing the nodes
of the list in order to perform some processing on
them.
• A linked list always contains a pointer variable
START which stores the address of the first node
of the list.
• End of the list is marked by storing NULL or –1 in
the NEXT field of the last node.
• For traversing the linked list, we also make use of
another pointer variable PTR which points to the
node that is currently being accessed.
Algorithm for traversing a linked list
Home work -
• write an pseudo code algorithm and C
Program to count the number of nodes in a
linked list.
An algorithm to count the number of
nodes in a linked list
Searching for a Value in a Linked List
• A linked list consists of nodes which are
divided into two parts, the information part
and the next part.
• searching means finding whether a given
value is present in the information part of the
node or not.
• If it is present, the algorithm returns the
address of the node that contains the value.
Example - Searching for a Value in a
Linked List
• Consider the following linked list.

• If we wants to search a node with VAL = 4,


then the flow of the algorithm can be
represented as follows:
Example - Searching for a Value in a
Linked List – cont.…
Algorithm to search a node from a
linked list
Homework :Question 1
• Write a C program to find sum of n elements
entered by user.
• Hint :To perform this program, allocate
memory dynamically using malloc() function.
• Answer
• https://www.programiz.com/c-
programming/c-dynamic-memory-allocation
Answer
Inserting a New Node in a Linked List
We will consider four insertion cases and then
see how insertion is done in each case.
• Case 1: The new node is inserted at the
beginning.
• Case 2: The new node is inserted at the end.
• Case 3: The new node is inserted after a given
node.
• Case 4: The new node is inserted before a
given node.
Case 1: Inserting a Node at the
Beginning of a Linked List
• Note : In all these four cases, let us first discuss an
important term called OVERFLOW.
• Overflow is a condition that occurs when AVAIL = NULL or
no free memory cell is present in the system. When this
condition occurs, the program must give an appropriate
message.
• Assume that a node to be inserted to the following
list(initial List).

• A new node with data part 9 to be inserted to the


beginning of the list.
Case 1: Inserting a Node at the
Beginning of a Linked List cont.….
Case 1: Inserting a Node at the
Beginning of a Linked List cont.….

AVAIL is
advanced
Case 2: Inserting a Node at the End of
a Linked List
• Suppose we want to add a new node with data 9 as the last
node of the list.
• Then the following changes will be done in the linked list.
• we take a pointer variable PTR and initialize it with START.
That is, PTR now points to the first node of the linked list.
• Using a while loop, we traverse through the linked list to
reach the last node. Once we reach the last node, we
change the NEXT pointer of the last node to store the
address of the new node.
• the NEXT field of the new node contains NULL,which
signifies the end of the linked list
Case 2: Inserting a Node at the End of
a Linked List: cont..
Case 2: Inserting a Node at the End of
a Linked List: cont..
Case 3: Inserting a Node After a Given
Node in a Linked List
• Suppose we want to add a new node with
value 9 after the node containing data 3.
Case 3: Inserting a Node After a Given
Node in a Linked List
Case 3: Inserting a Node After a Given
Node in a Linked List
Case 3: Inserting a Node After a Given
Node in a Linked List cont.….
Case 4: Inserting a Node Before a
Given Node in a Linked List

• Suppose we want to add a new node with


value 9 before the node containing 3.
Inserting a Node Before a Given Node
in a Linked List
Algorithm to insert a new node
before a node that has value NUM

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy