Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Array & Link List Data Structure

Uploaded by

0112cs221035
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Array & Link List Data Structure

Uploaded by

0112cs221035
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Data Structure and Algorithm

Arrays

An array is a linear data structure that collects elements of the same data
type and stores them in contiguous and adjacent memory locations.

Arrays work on an index system starting from 0 to (n-1), where n is the


size of the array.

➔Need of Array :

Let's suppose a class consists of ten students, and the class has to publish
their results. If you had declared all ten variables individually, it would be
challenging to manipulate and maintain the data.
Data Structure and Algorithm

If more students were to join, it would become more difficult to declare all
the variables and keep track of it. To overcome this problem, arrays came
into the picture.

➔Types of Arrays :

There are majorly two types of arrays, they are:

• One-Dimensional Arrays
• Multi-Dimensional Arrays

➔ One-Dimensional Arrays:

You can imagine a 1d array as a row, where elements are stored one after
another.

➔Multi-Dimensional Arrays:

These multi-dimensional arrays are again of two types. They are:

1. Two-Dimensional Arrays :
Data Structure and Algorithm

You can imagine it like a table where each cell contains elements.

2. Three-Dimensional Arrays:

You can imagine it like a cuboid made up of smaller cuboids where each
cuboid can contain an element.

In this "arrays in data structures" tutorial, you will work around one-
dimensional arrays.

➔Declaration of Array

Arrays are typically defined with square brackets with the size of the arrays
as its argument.

Here is the syntax for arrays:

• 1D Arrays: int arr[n];


Data Structure and Algorithm

• 2D Arrays: int arr[m][n];

• 3D Arrays: int arr[m][n][o];

➔Initialization of an Array

You can initialize an array in four different ways:

• Method 1:

int a[6] = {2, 3, 5, 7, 11, 13};

• Method 2:

int arr[]= {2, 3, 5, 7, 11};

• Method 3:

int n;
scanf(“%d”,&n);
int arr[n];
for(int i=0;i<5;i++)
{
scanf(“%d”,&arr[i]);
}

• Method 4:

int arr[4];
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
Data Structure and Algorithm

➔Accessing Elements of Arrays in Data Structures

You can access elements with the help of the index at which you stored
them. Let's discuss it with a code:

#include<stdio.h>
int main()
{
int a[5] = {2, 3, 5, 7, 11};
printf(“%d\n”,a[0]); // we are accessing
printf(“%d\n”,a[1]);
printf(“%d\n”,a[2]);
printf(“%d\n”,a[3]);
printf(“%d”,a[4]);
return 0;
}
OUTPUT :-
Data Structure and Algorithm

➔Advantages of Arrays

• Arrays store multiple elements of the same type with the same name.

• You can randomly access elements in the array using an index


number.

• Array memory is predefined, so there is no extra memory loss.

• Arrays avoid memory overflow.

• 2D arrays can efficiently represent the tabular data.

➔Disadvantages of Arrays

• The number of elements in an array should be predefined

• An array is static. It cannot alter its size after declaration.

• Insertion and deletion operation in an array is quite tricky as the array


stores elements in continuous form.

• Allocating excess memory than required may lead to memory


wastage

➔Basic Operations in the Arrays


The basic operations in the Arrays are insertion, deletion, searching,
display, traverse, and update. These operations are usually performed to
either modify the data in the array or to report the status of the array.
Following are the basic operations supported by an array.

• Traverse − print all the array elements one by one.


• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given index or by the
value.
• Update − Updates an element at the given index.
• Display − Displays the contents of the array.
Data Structure and Algorithm

➔Traversal Operation
This operation traverses through all the elements of an array. We use loop
statements to carry this out.

Example:-
public class ArrayDemo {
public static void main(String []args) {
int A[] = new int[5];
System.out.println("The array elements are: ");
for(int i = 0; i < 5; i++) {
A[i] = i + 2;
System.out.println("A[" + i + "] = " + A[i]);
}
}
}

OUTPUT:-

➔Insertion Operation
In the insertion operation, we are adding one or more elements to the
array. Based on the requirement, a new element can be added at the
beginning, end, or any given index of array. This is done using input
statements of the programming languages.

Example:-
public class ArrayDemo {
public static void main(String []args) {
int A[] = new int[3];
System.out.println("Array Before Insertion:");
for(int i = 0; i < 3; i++)
System.out.println("A[" + i + "] = " + A[i]); //prints
empty array
System.out.println("Inserting Elements..");
Data Structure and Algorithm

// Printing Array after Insertion


System.out.println("Array After Insertion:");
for(int i = 0; i < 3; i++) {
A[i] = i+3;
System.out.println("A[" + i + "] = " + A[i]);
}
}
}

OUTPUT:-

➔Deletion Operation
In this array operation, we delete an element from the particular index of
an array. This deletion operation takes place as we assign the value in the
consequent index to the current index.

Example:-
public class ArrayDemo {
public static void main(String []args) {
int A[] = new int[3];
int n = A.length;
System.out.println("Array Before Deletion:");
for(int i = 0; i < n; i++) {
A[i] = i + 3;
System.out.println("A[" + i + "] = " + A[i]);
}
for(int i = 1; i<n-1; i++) {
A[i] = A[i+1];
n = n - 1;
}
System.out.println("Array After Deletion:");
for(int i = 0; i < n; i++) {
System.out.println("A[" + i + "] = " + A[i]);
}
}
}
Data Structure and Algorithm

OUTPUT:-

➔Search Operation
Searching an element in the array using a key; The key element
sequentially compares every value in the array to check if the key is present
in the array or not.

Example:-
public class ArrayDemo{
public static void main(String []args){
int A[] = new int[5];
System.out.println("Array:");
for(int i = 0; i < 5; i++) {
A[i] = i + 3;
System.out.println("A[" + i + "] = " + A[i]);
}
for(int i = 0; i < 5; i++) {
if(A[i] == 6)
System.out.println("Element " + 6 + " is found at index " + i);
}
}
}

OUTPUT:-

➔Update Operation
Update operation refers to updating an existing element from the array at
a given index.
Data Structure and Algorithm

Example:-

public class ArrayDemo{


public static void main(String []args) {
int A[] = new int[5];
int item = 15;
System.out.println("The array elements are: ");
for(int i = 0; i < 5; i++) {
A[i] = i + 2;
System.out.println("A[" + i + "] = " + A[i]);
}
A[3] = item;
System.out.println("The array elements after updation are: ");
for(int i = 0; i < 5; i++)
System.out.println("A[" + i + "] = " + A[i]);
}
}

OUTPUT:-
Data Structure and Algorithm

➔Display Operation
This operation displays all the elements in the entire array using a print
statement.

Example:-
public class ArrayDemo {
public static void main(String []args) {
int A[] = new int[5];
System.out.println("The array elements are: ");
for(int i = 0; i < 5; i++) {
A[i] = i + 2;
System.out.println("A[" + i + "] = " + A[i]);
}
}
}

OUTPUT:-
Data Structure and Algorithms

Linked Lists

Linked lists and arrays are similar since they both store collections of
data. Array is the most common data structure used to store collections of
elements. Arrays are convenient to declare and provide the easy syntax to
access any element by its index number. Once the array is set up, access
to any element is convenient and fast.

The disadvantages of arrays are:

• The size of the array is fixed. Most often this size is specified at
compile time. This makes the programmers to allocate arrays,
which seems "large enough" than required.

• Inserting new elements at the front is potentially expensive


because existing elements need to be shifted over to make room.

• Deleting an element from an array is not possible.

Linked lists have their own strengths and weaknesses, but they happen to
be strong where arrays are weak. Generally array's allocates the memory
for all its elements in one block whereas linked lists use an entirely different
strategy. Linked lists allocate memory for each element separately and only
when necessary.

Here is a quick review of the terminology and rules of pointers. The


linked list code will depend on the following functions:

• malloc()
• free()

➔malloc()

malloc() is a system function which allocates a block of memory in the


"heap" and returns a pointer to the new block. The prototype of malloc()
and other heap functions are in stdlib.h. malloc() returns NULL if it cannot
fulfill the request. It is defined by:

void *malloc (number_of_bytes)


Data Structure and Algorithms

Since a void * is returned the C standard states that this pointer can be
converted to any type. For example,
char *cp;
cp = (char *) malloc (100);

Attempts to get 100 bytes and assigns the starting address to cp. We can
also use the sizeof() function to specify the number of bytes. For example,

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

➔free()
free() is the opposite of malloc(), which de-allocates memory. The
argument to free() is a pointer to a block of memory in the heap — a pointer
which was obtained by a malloc() function. The syntax is:

free (ptr);

The advantage of free() is simply memory management when we no longer


need a block.

➔ Linked List Concepts:

A linked list is a non-sequential collection of data items. It is a dynamic data


structure. For every data item in a linked list, there is an associated pointer
that would give the memory location of the next data item in the linked list.

The data items in the linked list are not in consecutive memory locations.
They may be anywhere, but the accessing of these data items is easier as
each data item contains the address of the next data item.

➔ Advantages of linked lists:

Linked lists have many advantages. Some of the very important advantages
are:

1. Linked lists are dynamic data structures. i.e., they can grow or
shrink during the execution of a program.
2. Linked lists have efficient memory utilization. Here, memory is not
preallocated. Memory is allocated whenever it is required and it is
de-allocated (removed) when it is no longer needed.
Data Structure and Algorithms

3. Insertion and Deletions are easier and efficient. Linked lists


provide flexibility in inserting a data item at a specified position
and deletion of the data item from the given position.
4. Many complex applications can be easily carried out with linked
lists.

➔ Disadvantages of linked lists:

1. It consumes more space because every node requires a additional


pointer to store address of the next node.
2. Searching a particular element in list is difficult and also time
consuming.

➔Types of Linked Lists:

Basically we can put linked lists into the following four items:

1. Single Linked List.


2. Double Linked List.
3. Circular Linked List.
4. Circular Double Linked List.

A single linked list is one in which all nodes are linked together in some
sequential manner. Hence, it is also called as linear linked list.

A double linked list is one in which all nodes are linked together by
multiple links which helps in accessing both the successor node (next node)
and predecessor node (previous node) from any arbitrary node within the
list. Therefore each node in a double linked list has two link fields (pointers)
to point to the left node (previous) and the right node (next). This helps to
traverse in forward direction and backward direction.

A circular linked list is one, which has no beginning and no end. A single
linked list can be made a circular linked list by simply storing address of the
very first node in the link field of the last node.

A circular double linked list is one, which has both the successor pointer
and predecessor pointer in the circular manner.
Data Structure and Algorithms

➔ Comparison between array and linked list:

ARRAY LINKED LIST

Size of an array is fixed Size of a list is not fixed

Memory is allocated from stack Memory is allocated from heap


It is necessary to specify the It is not necessary to specify the
number of elements during number of elements during
declaration (i.e., during compile declaration (i.e., memory is
time). allocated during run time).
It occupies less memory than a It occupies more memory.
linked list for the same number of
elements.
Inserting new elements at the Inserting a new element at any
front is potentially expensive position can be carried out easily.
because existing elements need to
be shifted over to make room.
Deleting an element from an array Deleting an element is possible.
is not possible.

➔ Trade offs between linked lists and arrays:

FEATURE ARRAYS LINKED LISTS

Sequential access efficient efficient

Random access efficient inefficient

Resigning inefficient efficient

Element rearranging inefficient efficient

Overhead per none 1 or 2 links


elements
Data Structure and Algorithms

➔ Applications of linked list:

1. Linked lists are used to represent and manipulate polynomial.


Polynomials are expression containing terms with non zero coefficient
and exponents. For example:

P(x) = a0 Xn + a1 Xn-1 + …… + an-1 X + an

2. Represent very large numbers and operations of the large number


such as addition, multiplication and division.

3. Linked lists are to implement stack, queue, trees and graphs.

4. Implement the symbol table in compiler construction

1. 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.

A single linked list is shown in figure 1.

STACK HEAP

100
start
10 200 20 300 30 400 40 X
100 200 300 400
The start
pointer holds
Each node stores Stores the next
the address The next field of the
the data. node address.
of the first last node is NULL.
node of the
list.

Figure 1. Single Linked List

The beginning of the linked list is stored in a "start" pointer which points
to the first node. The first node contains a pointer to the second node. The
second node contains a pointer to the third node, ... and so on. The last
Data Structure and Algorithms

node in the list has its next field set to NULL to mark the end of the list.
Code can access any node in the list by starting at the start and following
the next pointers.

The start pointer is an ordinary local pointer variable, so it is drawn


separately on the left top to show that it is in the stack. The list nodes are
drawn on the right to show that they are allocated in the heap.

➔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. The following
structure definition will do (see figure 2):

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

• Initialise the start pointer to be NULL.

struct slinklist data next


{ node:
int data;
struct slinklist *next;
};
typedef struct slinklist node; NULL
node *start = NULL;
start
Empty list:
Figure 2, Structure definition, single link node and empty
list
Data Structure and Algorithms

➔The basic operations in a single linked list are:

• Creation.
• Insertion.
• Deletion.
• Traversing.

1. 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.
Figure 3 illustrates the creation of a node for single linked list.

node *getnode()
{ newnode
node *newnode;
10 X
newnode = (node
*)malloc(sizeof(node)); 100
printf("\n Enter data: ");
scanf("%d", &newnode->data);
newnode->next = NULL;
return newnode;
}
Figure 3. new node 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:

• Get the new node using getnode(). newnode = getnode();

• If the list is empty, assign new node as start. start = newnode;

• If the list is not empty, follow the steps given below:

• The next field of the new node is made to point the first node (i.e.
Data Structure and Algorithms

start node) in the list by assigning the address of the first node.

• The start pointer is made to point the new node by assigning the
address of the new node.

• Repeat the above steps ‘n’ times.

Figure 4, shows 4 items in a single linked list stored at different locations in


memory.

start
100

10 200 20 300 30 400 40 X


100 200 300 400

Figure 4, Single Linked List with 4 nodes

The function createlist(), is used to create ‘n’ number of nodes:

void createlist(int n)
{
int i;
node *newnode;
node *temp;
for(i = 0; i < n ; i++)
{
newnode = getnode();
if(start == NULL)
{
start = newnode;
}
else
{
temp = start;
while(temp -> next
!= NULL)
temp = temp -> next;
temp -> next = newnode;
}
}
}

2. Insertion of a Node:
Data Structure and Algorithms

One of the most primitive operations that can be done in a singly linked list
is the insertion of a node. Memory is to be allocated for the new node (in a
similar way that is done while creating a list) before reading the data. The
new node will contain empty data field and empty next field. The data field
of the new node is then stored with the information read from the user. The
next field of the new node is assigned to NULL.
The new node can then be inserted at three different places namely:

• Inserting a node at the beginning.


• Inserting a node at the end.
• Inserting a node at intermediate position.

Inserting a node at the beginning:

The following steps are to be followed to insert a new node at the beginning
of the list:

• Get the new node using getnode(). newnode = getnode();

• If the list is empty then start = newnode.

• If the list is not empty, follow the steps given below: newnode -
> next = start;
start = newnode;

Figure 5 shows inserting a node into the single linked list at the beginning.

start
500

10 200 20 300 30 400 40 X


100 200 300 400

5 100
500

Figure 5, Inserting a node at the beginning

The function insert_at_beg(), is used for inserting a node at the beginning


Data Structure and Algorithms

void insert_at_beg()
{
node
*newnode;
newnode =
getnode();
if(start == NULL)
{
start = newnode;
}
else
{
newnode -> next = start;
start = newnode;
}
}

Inserting a node at the end:

The following steps are followed to insert a new node at the end of the list:

• Get the new node using getnode() newnode = getnode();

• If the list is empty then start = newnode.

• If the list is not empty follow the steps given


below: temp = start;
while(temp -> next != NULL)
temp = temp -> next;
temp -> next = newnode;

Figure 6 shows inserting a node into the single linked list at the end.

start
100

10 200 20 300 30 400 40 500


100 200 300 400

50 X
500

Figure 6, Inserting a node at the end.


Data Structure and Algorithms

The function insert_at_end(), is used for inserting a node at the end.

void insert_at_end()
{
node *newnode, *temp;
newnode = getnode();
if (start == NULL)
{
start = newnode;
}
else
{
temp = start;
while (temp->next != NULL)
temp = temp->next;
temp->next = newnode;
}
}

Inserting a node at intermediate position:

The following steps are followed, to insert a new node in an intermediate


position in the list:
• Get the new node using getnode(). newnode = getnode();
• Ensure that the specified position is in between first node and last
node. If not, specified position is invalid. This is done by
countnode() function.

• Store the starting address (which is in start pointer) in temp and


prev pointers. Then traverse the temp pointer upto the specified
position followed by prev pointer.

• After reaching the specified position, follow the steps given below:
prev -> next = newnode;
newnode -> next = temp;

• Let the intermediate position be 3.

Figure 7 shows inserting a node into the single linked list at a specified
intermediate position other than beginning and end.
Data Structure and Algorithms

start prev temp


100

10 200 20 500 30 400 40 X


100 200 300 400

50 300
500 new node

Figure 7. Inserting a node at an intermediate position.

The function insert_at_mid(), is used for inserting a node in the


intermediate position.

void insert_at_mid()
{
node *newnode, *temp, *prev;
int pos, nodectr, ctr = 1;
newnode = getnode();
printf("\n Enter the position: ");
scanf("%d", &pos);
nodectr = countnode(start);
if (pos > 1 && pos < nodectr)
{
temp = prev = start;
while (ctr < pos)
{
prev = temp;
temp = temp->next;
ctr++;
}
prev->next = newnode;
newnode->next = temp;
}
else
{
printf("position %d is not a middle position",
pos);
}
}
Data Structure and Algorithms

Deletion of a node:

Another primitive operation that can be done in a singly linked list is the
deletion of a node. Memory is to be released for the node to be deleted. A
node can be deleted from the list from three different places namely.

• Deleting a node at the beginning.


• Deleting a node at the end.
• Deleting a node at intermediate position.

Deleting a node at the beginning:

The following steps are followed, to delete a node at the beginning of the
list:

• If list is empty then display ‘Empty List’ message.

• If the list is not empty, follow the steps given below:


temp = start;
start = start -> next;
free(temp);

Figure shows deleting a node at the beginning of a single linked list.

start
200

10 200 20 300 30 400 40 X


100 200 300 400
temp

Figure 8 Deletion a node at the begingng


g .

The function delete_at_beg(), is used for deleting the first node in the list.
Data Structure and Algorithms

void delete_at_beg()
{
node *temp;
if(start == NULL)
{
printf("\n No nodes are
exist..");
return ;
}
else
{
temp = start;
start = temp -> next;
free(temp);
printf("\n Node deleted
");
}
}

Deleting a node at the end:

The following steps are followed to delete a node at the end of the list:

• If list is empty then display ‘Empty List’ message.

• If the list is not empty, follow the steps given below:

temp = prev = start;


while(temp -> next != NULL)
{
prev = temp;
temp = temp -> next;
}
prev -> next = NULL;
free(temp);

Figure 9 shows deleting a node at the end of a single linked list.


Data Structure and Algorithms

start
100

10 200 20 300 30 X 40 X
100 200 300 400

Figure 9. Deleting a node at the end.

The function delete_at_last(), is used for deleting the last node in the list.

void delete_at_last()
{
node *temp, *prev;
if (start == NULL)
{
printf("\n Empty List..");
return;
}
else
{
temp = start;
prev = start;
while (temp->next != NULL)
{
prev = temp;
temp = temp->next;
}
prev->next = NULL;
free(temp);
printf("\n Node deleted ");
}
}
Data Structure and Algorithms

Deleting a node at Intermediate position:

The following steps are followed, to delete a node from an intermediate


position in the list (List must contain more than two node).

• If list is empty then display ‘Empty List’ message

• If the list is not empty, follow the steps given below.


if(pos > 1 && pos < nodectr)
{
temp = prev = start;
ctr = 1;
while(ctr < pos)
{
prev = temp;
temp = temp -> next;
ctr++;
}
prev -> next = temp -> next;
free(temp);
printf("\n node deleted..");
}

Figure 10, shows deleting a node at a specified intermediate position other


than beginning and end from a single linked list.

start
100

10 300 20 300 30 400 40 X


100 200 300 400

Figure 10, Deleting a node at an intermediate position.

The function delete_at_mid(), is used for deleting the intermediate node in


the list.
Data Structure and Algorithms

void delete_at_mid()
{
int ctr = 1, pos, nodectr;
node *temp, *prev;
if (start == NULL)
{
printf("\n Empty List..");
return;
}
else
{
printf("\n Enter position of node to delete: ");
scanf("%d", &pos);
nodectr = countnode(start);
if (pos > nodectr)
{
printf("\nThis node doesnot exist");
}
if (pos > 1 && pos < nodectr)
{
temp = prev = start;
while (ctr < pos)
{
prev = temp;
temp = temp->next;
ctr++;
}
prev->next = temp->next;
free(temp);
}
else
{
printf("\n Node deleted..");
printf("\n Invalid position..");
}
getch();
}
}
Data Structure and Algorithms

Traversal and displaying a list (Left to Right):

To display the information, you have to traverse (move) a linked list, node
by node from the first node, until the end of the list is reached. Traversing
a list involves the following steps:

• Assign the address of start pointer to a temp pointer.


• Display the information from the data field of each node.

The function traverse() is used for traversing and displaying the information
stored in the list from left to right.

void traverse()
{
Node *temp;
temp = start;
printf("\n The contents of List (Left to Right):
\n"); if(start == NULL )
printf("\n Empty List");
else
{
while (temp != NULL)
{
printf("%d ->", temp -> data);
temp = temp -> next;
}
}
printf("X");
}

Alternatively there is another way to traverse and display the information.


That is in reverse order. The function rev_traverse(), is used for traversing
and displaying the information stored in the list from right to left.

void rev_traverse(node *st)


{
if(st == NULL)
{
return;
}
else
{
rev_traverse(st->next);
printf("%d ->", st -> data);
Data Structure and Algorithms

}
}

Counting the Number of Nodes:

The following code will count the number of nodes exist in the list using
recursion.

int countnode(node *st)


{
if(st==NULL)
return 0;
else
return(1 + countnode(st -> next));
}

Source Code for the Implementation of Single Linked


List:
class Node {
int data;
Node next;

public Node(int data) {


this.data = data;
this.next = null;
}
}

class LinkedList {
private Node head;

public LinkedList() {
head = null;
}

// Insertion at the end of the linked list


Data Structure and Algorithms

public void insert(int data) {


Node newNode = new Node(data);

if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}

// Deletion of a node with given data


public void delete(int data) {
if (head == null) {
return;
}

if (head.data == data) {
head = head.next;
return;
}

Node current = head;


Node prev = null;

while (current != null && current.data != data) {


prev = current;
current = current.next;
}

if (current != null) {
prev.next = current.next;
}
}
Data Structure and Algorithms

// Display elements of the linked list


public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
}

public class LinkedListExample {


public static void main(String[] args) {
LinkedList list = new LinkedList();

list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);

System.out.println("Initial Linked List:");


list.display();

list.delete(2);
System.out.println("Linked List after deleting
2:");
list.display();
}
}

OUTPUT:-

Initial Linked List:


1 -> 2 -> 3 -> 4 -> null
Linked List after deleting 2:
1 -> 3 -> 4 -> null
Data Structure and Algorithms

Using a header node:

A header node is a special dummy node found at the front of the list. The
use of header node is an alternative to remove the first node in a list. For
example, the picture below shows how the list with data 10, 20 and 30
would be represented using a linked list without and with a header node:

start
100

10 200 20 300 30 X
100 200 300

Single Linked List without a header node

start
400

100 10 200 20 300 30 X


400 100 200 300

Single Linked List with header node

Note that if your linked lists do include a header node, there is no need for
the special case code given above for the remove operation; node n can
never be the first node in the list, so there is no need to check for that case.
Similarly, having a header node can simplify the code that adds a node
before a given node n.
Note that if you do decide to use a header node, you must remember to
initialize an empty list to contain one (dummy) node, you must remember
not to include the header node in the count of "real" nodes in the list.

It is also useful when information other than that found in each node of the
list is needed. For example, imagine an application in which the number of
items in a list is often calculated. In a standard linked list, the list function
to count the number of nodes has to traverse the entire list every time.
However, if the current length is maintained in a header node, that
information can be obtained very quickly.

Array based linked lists:

Another alternative is to allocate the nodes in blocks. In fact, if you know


the maximum size of a list a head of time, you can pre-allocate the nodes
Data Structure and Algorithms

in a single array. The result is a hybrid structure – an array based linked


list. Figure shows an example of null terminated single linked list where
all the nodes are allocated contiguously in an array.

start
100 a

b
a 200 b 300 c X
100 200 300 c

Conceptual structure d

Implementation

Figure 3.5.1. An array based linked list

2. Double Linked List:

A double linked list is a two-way list in which all nodes will have two links.
This helps in accessing both successor node and predecessor node from the
given node position. It provides bi-directional traversing. Each node
contains three fields:

• Left link.
• Data.
• Right link.

The left link points to the predecessor node and the right link points to the
successor node. The data field stores the required data.

Many applications require searching forward and backward thru nodes of a


list. For example searching for a name in a telephone directory would
need forward and backward scanning thru a region of the whole list.

The basic operations in a double linked list are:

• Creation.
• Insertion.
• Deletion.
• Traversing.

A double linked list is shown in figure2.1.


Data Structure and Algorithms

STACK HEAP
Stores the previous
node address.
100
start
X 10 200 100 20 300 200 30 X
100 200 300
The start
pointer holds
the address Stores the data. Stores the next The right field of the
of the first node address. last node is NULL.
node of the
list.

Figure 2.1 Double Linked List

The beginning of the double linked list is stored in a "start" pointer which
points to the first node. The first node’s left link and last node’s right link is
set to NULL.

The following code gives the structure definition:

struct dlinklist node: left data right


{
struct dlinklist
*left; int data;
struct dlinklist *right;
NULL
};
start
typedef struct dlinklist Empty list:
node; node *start =
NULL;
Figure Structure definition, double link node and empty list

➔ Creating a node for Double Linked List:

Creating a double 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 and set left field to NULL and right field also set to NULL (see figure
2.2).
Data Structure and Algorithms

node* getnode()
{
node* newnode; newnode
newnode = (node *)malloc(sizeof(node)); X 10 X
printf("\n Enter data: ");
100
scanf("%d",&newnode->data);
newnode->left=NULL;
newnode->right=NULL;
return newnode;
}
Figure 2.2 new node with a value of 10

Creating a Double Linked List with ‘n’ number of nodes:

The following steps are to be followed to create ‘n’ number of nodes:

• Get the new node using getnode().


newnode =getnode();

• If the list is empty then start = newnode.

• If the list is not empty, follow the steps given below:

• The left field of the new node is made to point the previous node.

• The previous nodes right field must be assigned with address of


the new node.

• Repeat the above steps ‘n’ times.

The function createlist(), is used to create ‘n’ number of nodes:


Data Structure and Algorithms

void createlist(int n)
{
int i;
node *newnode;
node *temp;
for (i = 0; i < n; i++)
{
newnode = getnode();
if (start == NULL)
{
start = newnode;
}
else
{
temp = start;
while (temp->right)
temp = temp->right;
temp->right = newnode;
newnode->left = temp;
}
}
}

Figure shows 3 items in a double linked list stored at different locations.

start
100

X 10 200 100 20 300 200 30 X


100 200 300

Figure Double Linked List with 3 nodes

Inserting a node at the beginning:

The following steps are to be followed to insert a new node at the beginning
of the list:

• Get the new node using getnode().


Data Structure and Algorithms

newnode=getnode();

• If the list is empty then start = newnode.

• If the list is not empty, follow the steps given below:

newnode -> right = start;


start -> left = newnode;
start = newnode;

The function dbl_insert_beg(), is used for inserting a node at the beginning.


Figure shows inserting a node into the double linked list at the beginning.

start
400

400 10 200 100 20 300 200 30 X


100 200 300

X 40 100
400

Figure Inserting a node at the beginning

Inserting a node at the end:

The following steps are followed to insert a new node at the end of the list:

• Get the new node using getnode()


newnode=getnode();

• If the list is empty then start = newnode.

• If the list is not empty follow the steps given below:

temp = start;
while(temp -> right != NULL)
temp = temp -> right;
temp -> right = newnode;
newnode -> left = temp;
Data Structure and Algorithms

The function dbl_insert_end(), is used for inserting a node at the end.


Figure shows inserting a node into the double linked list at the end.

start
100

X 10 200 100 20 300 200 30 400

100 200 300

300 40 X
400

Figure Inserting a node at the end

Inserting a node at an intermediate position:

The following steps are followed, to insert a new node in an intermediate


position in the list:
• Get the new node using getnode().
newnode=getnode();

• Ensure that the specified position is in between first node and last
node. If not, specified position is invalid. This is done by
countnode() function.

• Store the starting address (which is in start pointer) in temp and


prev pointers. Then traverse the temp pointer upto the specified
position followed by prev pointer.

• After reaching the specified position, follow the steps given below:

newnode -> left = temp;


newnode -> right = temp -> right;
temp -> right -> left = newnode;
temp -> right = newnode;

The function dbl_insert_mid(), is used for inserting a node in the


intermediate position. Figure shows inserting a node into the double linked
list at a specified intermediate position other than beginning and end.
Data Structure and Algorithms

start
100 40 200
100
400
400 20 300
X 10 400
200
100

200 30 X
300

Figure Inserting a node at an intermediate position

Deleting a node at the beginning:

The following steps are followed, to delete a node at the beginning of the
list:

• If list is empty then display ‘Empty List’ message.

• If the list is not empty, follow the steps given below:

temp = start;
start = start -> right;
start -> left = NULL;
free(temp);

The function dbl_delete_beg(), is used for deleting the first node in the list.
Figure shows deleting a node at the beginning of a double linked list.

start
200

X 10 200 X 20 300 200 30 X


100 200 300

Figure Deleting a node at beginning

Deleting a node at the end:

The following steps are followed to delete a node at the end of the list:
• If list is empty then display ‘Empty List’ message
Data Structure and Algorithms

• If the list is not empty, follow the steps given below:

temp = start;
while(temp -> right != NULL)
{
temp = temp -> right;
}
temp -> left -> right = NULL;
free(temp);

The function dbl_delete_last(), is used for deleting the last node in the list.
Figure shows deleting a node at the end of a double linked list.

start
100

X 10 200 100 20 X 200 30 X


100 200 300

Figure Deleting a node at the end

Deleting a node at Intermediate position:

The following steps are followed, to delete a node from an intermediate


position in the list (List must contain more than two nodes).

• If list is empty then display ‘Empty List’ message.

• If the list is not empty, follow the steps given below:

• Get the position of the node to delete.

• Ensure that the specified position is in between first node


and last node. If not, specified position is invalid.

• Then perform the following steps:


if(pos > 1 && pos < nodectr)
{
temp = start;
i = 1;
while(i < pos)
Data Structure and Algorithms

{
temp = temp -> right;
i++;
}
temp -> right -> left = temp -> left;
temp -> left -> right = temp -> right;
free(temp);
printf("\n node deleted..");
}

The function delete_at_mid(), is used for deleting the intermediate node in


the list. Figure shows deleting a node at a specified intermediate position
other than beginning and end from a double linked list.

start
100

X 10 300 100 20 300 100 30 X


100 200 300

Figure Deleting a node at an intermediate position

Traversal and displaying a list (Left to Right):

To display the information, you have to traverse the list, node by node from
the first node, until the end of the list is reached. The function
traverse_left_right() is used for traversing and displaying the information
stored in the list from left to right.

The following steps are followed, to traverse a list from left to right:

• If list is empty then display ‘Empty List’ message.

• If the list is not empty, follow the steps given below:

temp = start;
while(temp != NULL)
{
print temp -> data;
temp = temp -> right;
}
Data Structure and Algorithms

Traversal and displaying a list (Right to Left):

To display the information from right to left, you have to traverse the list,
node by node from the first node, until the end of the list is reached. The
function traverse_right_left() is used for traversing and displaying the
information stored in the list from right to left. The following steps are
followed, to traverse a list from right to left:
• If list is empty then display ‘Empty List’ message.

• If the list is not empty, follow the steps given below:

temp = start;
while (temp->right != NULL)
temp = temp->right;
while (temp != NULL)
{
print temp->data;
temp = temp->left;
}

Counting the Number of Nodes:

The following code will count the number of nodes exist in the list (using
recursion).

int countnode(node *start)


{
if (start == NULL)
return 0;
else
return (1 + countnode(start->right));
}

A Complete Source Code for the Implementation of Double


Linked List:
Data Structure and Algorithms

class Node {
int data;
Node prev;
Node next;

public Node(int data) {


this.data = data;
this.prev = null;
this.next = null;
}
}

class DoublyLinkedList {
private Node head;
private Node tail;

public DoublyLinkedList() {
head = null;
tail = null;
}

// Insertion at the beginning of the linked list


public void insertAtBeginning(int data) {
Node newNode = new Node(data);

if (head == null) {
head = newNode;
tail = newNode;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
}

// Insertion at the end of the linked list


public void insertAtEnd(int data) {
Data Structure and Algorithms

Node newNode = new Node(data);

if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
}

// Deletion of a node with given data


public void delete(int data) {
if (head == null) {
return;
}

if (head.data == data) {
if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
head.prev = null;
}
return;
}

if (tail.data == data) {
tail = tail.prev;
tail.next = null;
return;
}

Node current = head;


while (current != null && current.data != data) {
current = current.next;
Data Structure and Algorithms

if (current != null) {
current.prev.next = current.next;
current.next.prev = current.prev;
}
}

// Display elements of the linked list in forward direction


public void displayForward() {
Node current = head;
while (current != null) {
System.out.print(current.data + " <-> ");
current = current.next;
}
System.out.println("null");
}

// Display elements of the linked list in backward direction


public void displayBackward() {
Node current = tail;
while (current != null) {
System.out.print(current.data + " <-> ");
current = current.prev;
}
System.out.println("null");
}
}

public class DoublyLinkedListExample {


public static void main(String[] args) {
DoublyLinkedList list = new DoublyLinkedList();

list.insertAtEnd(1);
list.insertAtEnd(2);
list.insertAtBeginning(0);
list.insertAtEnd(3);
Data Structure and Algorithms

System.out.println("Doubly Linked List (Forward):");


list.displayForward();

System.out.println("Doubly Linked List (Backward):");


list.displayBackward();

list.delete(2);
System.out.println("Doubly Linked List after deleting 2
(Forward):");
list.displayForward();

list.delete(0);
System.out.println("Doubly Linked List after deleting 0
(Forward):");
list.displayForward();
}
}

OUTPUT:-

Doubly Linked List (Forward):


0 <-> 1 <-> 2 <-> 3 <-> null
Doubly Linked List (Backward):
3 <-> 2 <-> 1 <-> 0 <-> null
Doubly Linked List after deleting 2 (Forward):
0 <-> 1 <-> 3 <-> null
Doubly Linked List after deleting 0 (Forward):
1 <-> 3 <-> null
Data Structure and Algorithms

3. Circular Single Linked List:

It is just a single linked list in which the link field of the last node points
back to the address of the first node. A circular linked list has no beginning
and no end. It is necessary to establish a special pointer called start pointer
always pointing to the first node of the list. Circular linked lists are
frequently used instead of ordinary linked list because many operations are
much easier to implement. In circular linked list no null pointers are used,
hence all pointers contain valid address.

A circular single linked list is shown in figure.

start
100

10 200 20 300 30 400 40 100


100 200 300 400

Figure Circular Single Linked List

The basic operations in a circular single linked list are:

• Creation.
• Insertion.
• Deletion.
• Traversing.

Creating a circular single Linked List with ‘n’ number of nodes:

The following steps are to be followed to create ‘n’ number of nodes:

• Get the new node using getnode().

newnode = getnode();

• If the list is empty, assign new node as start.

start = newnode;

• If the list is not empty, follow the steps given below:


Data Structure and Algorithms

temp = start;
while (temp->next != NULL)
temp = temp->next;
temp->next = newnode;

• Repeat the above steps ‘n’ times.

• newnode -> next = start;

The function createlist(), is used to create ‘n’ number of nodes:

Inserting a node at the beginning:

The following steps are to be followed to insert a new node at the beginning
of the circular list:
• Get the new node using getnode().

newnode = getnode();

• If the list is empty, assign new node as start.

start = newnode;
newnode -> next = start;

• If the list is not empty, follow the steps given below:

last = start;
while (last->next != start)
last = last->next;
newnode->next = start;
start = newnode;
last->next = start;
The function cll_insert_beg(), is used for inserting a node at the beginning.
Figure shows inserting a node into the circular single linked list at the
beginning.
Data Structure and Algorithms

start
500

10 200 20 300 30 400 40 500


100 200 300 400

5 100
500

Figure Inserting a node at the beginning

Inserting a node at the end:

The following steps are followed to insert a new node at the end of the list:

• Get the new node using getnode().

newnode = getnode();

• If the list is empty, assign new node as start.

start = newnode;
newnode -> next = start;

• If the list is not empty follow the steps given below:

temp = start;
while(temp -> next != start)
temp = temp -> next;
temp -> next = newnode;
newnode -> next = start;

The function cll_insert_end(), is used for inserting a node at the end.


Figure shows inserting a node into the circular single linked list at the end.

start
100

10 200 20 300 30 400 40 500


100 200 300 400

50 100
500

Figure Inserting a node at the end.


Data Structure and Algorithms

Deleting a node at the beginning:

The following steps are followed, to delete a node at the beginning of the
list:

• If the list is empty, display a message ‘Empty List’.

• If the list is not empty, follow the steps given below:

last = temp = start;


while (last->next != start)
last = last->next;
start = start->next;
last->next = start;

• After deleting the node, if the list is empty then start = NULL.

The function cll_delete_beg(), is used for deleting the first node in the list.
Figure shows deleting a node at the beginning of a circular single linked list.

start
200

10 200 20 300 30 400 40 200


100 200 300 400
temp

Figure Deleting a node at beginning.

Deleting a node at the end:

The following steps are followed to delete a node at the end of the list:

• If the list is empty, display a message ‘Empty List’.

• If the list is not empty, follow the steps given below:

temp = start;
prev = start;
while(temp -> next != start)
{
prev = temp;
temp = temp -> next;
Data Structure and Algorithms

}
prev -> next = start;

• After deleting the node, if the list is empty then start = NULL.

The function cll_delete_last(), is used for deleting the last node in the list.
Figure shows deleting a node at the end of a circular single linked list.

start
100

10 200 20 300 30 100 40 100


100 200 300 400

Figure Deleting a node at the end.

Traversing a circular single linked list from left to right:

The following steps are followed, to traverse a list from left to right:

• If list is empty then display ‘Empty List’ message.

• If the list is not empty, follow the steps given below:

temp = start;
do
{
printf("%d ", temp -> data);
temp = temp -> next;
} while(temp != start);
Data Structure and Algorithms

Source Code for Circular Single Linked List:


class Node {
int data;
Node next;

public Node(int data) {


this.data = data;
this.next = null;
}
}

class CircularSinglyLinkedList {
private Node head;
private Node tail;

public CircularSinglyLinkedList() {
head = null;
tail = null;
}

// Insertion at the beginning of the linked list


public void insertAtBeginning(int data) {
Node newNode = new Node(data);

if (head == null) {
head = newNode;
head.next = head; // Circular reference
tail = head;
} else {
newNode.next = head;
head = newNode;
tail.next = head; // Update the tail's next to maintain the
circular structure
}
}

// Insertion at the end of the linked list


public void insertAtEnd(int data) {
Node newNode = new Node(data);

if (head == null) {
head = newNode;
head.next = head; // Circular reference
Data Structure and Algorithms

tail = head;
} else {
tail.next = newNode;
newNode.next = head;
tail = newNode;
}
}

// Deletion of a node with given data


public void delete(int data) {
if (head == null) {
return;
}

if (head.data == data) {
if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
tail.next = head; // Update the tail's next to maintain
the circular structure
}
return;
}

Node current = head;


Node prev = null;

while (current != tail && current.data != data) {


prev = current;
current = current.next;
}

if (current != tail) {
prev.next = current.next;
}
}

// Display elements of the linked list in a circular manner


public void display() {
Node current = head;

if (current == null) {
Data Structure and Algorithms

System.out.println("Circular Singly Linked List is


empty.");
return;
}

System.out.print("Circular Singly Linked List: ");


do {
System.out.print(current.data + " -> ");
current = current.next;
} while (current != head);

System.out.println(head.data + " (Head)");


}
}

public class CircularSinglyLinkedListExample {


public static void main(String[] args) {
CircularSinglyLinkedList list = new CircularSinglyLinkedList();

list.insertAtEnd(1);
list.insertAtEnd(2);
list.insertAtBeginning(0);
list.insertAtEnd(3);

list.display();

list.delete(2);
System.out.println("Circular Singly Linked List after deleting
2:");
list.display();
}
}

OUTPUT:-

Circular Singly Linked List: 0 -> 1 -> 2 -> 3 (Head)


Circular Singly Linked List after deleting 2:
Circular Singly Linked List: 0 -> 1 -> 3 (Head)

4. Circular Double Linked List:


Data Structure and Algorithms

A circular double linked list has both successor pointer and predecessor
pointer in circular manner. The objective behind considering circular double
linked list is to simplify the insertion and deletion operations performed on
double linked list. In circular double linked list the right link of the right
most node points back to the start node and left link of the first node points
to the last node. A circular double linked list is shown in figure .

100

start 300 10 200 100 20 300 200 30 100

100 200 300

Figure Circular Double Linked List

The basic operations in a circular double linked list are:

• Creation.
• Insertion.
• Deletion.
• Traversing.

Creating a Circular Double Linked List with ‘n’ number of


nodes:

The following steps are to be followed to create ‘n’ number of nodes:

• Get the new node using getnode(). newnode = getnode();

• If the list is empty, then do the following


start = newnode;
newnode -> left = start;
newnode ->right = start;

• If the list is not empty, follow the steps given below:


newnode -> left = start -> left;
newnode -> right = start;
start -> left->right = newnode;
start -> left = newnode;

• Repeat the above steps ‘n’ times.

The function cdll_createlist(), is used to create ‘n’ number of nodes:


Data Structure and Algorithms

Inserting a node at the beginning:

The following steps are to be followed to insert a new node at the beginning
of the list:

• Get the new node using getnode(). newnode=getnode();

• If the list is empty, then


start = newnode;
newnode -> left = start;
newnode -> right = start;

• If the list is not empty, follow the steps given below:


newnode -> left = start -> left;
newnode -> right = start;
start -> left -> right = newnode;
start -> left = newnode;
start = newnode;

The function cdll_insert_beg(), is used for inserting a node at the beginning.


Figure shows inserting a node into the circular double linked list at the
beginning.

start

400

400 10 200 100 20 300 200 30 400

100 200 300

300 40 100

400

Figure Inserting a node at the beginning

Inserting a node at the end:

The following steps are followed to insert a new node at the end of the list:

• Get the new node using getnode() newnode=getnode();

• If the list is empty, then


start = newnode;
Data Structure and Algorithms

newnode -> left = start;


newnode -> right = start;

• If the list is not empty follow the steps given below:


newnode -> left = start -> left;
newnode -> right = start;
start -> left -> right = newnode;
start -> left = newnode;

The function cdll_insert_end(), is used for inserting a node at the end.


Figure shows inserting a node into the circular linked list at the end.

start

100

400 10 200 100 20 300 200 30 400

100 200 300

300 40 100

400

Figure Inserting a node at the end

Inserting a node at an intermediate position:

The following steps are followed, to insert a new node in an intermediate


position in the list:
• Get the new node using getnode(). newnode=getnode();

• Ensure that the specified position is in between first node and last
node. If not, specified position is invalid. This is done by
countnode() function.

• Store the starting address (which is in start pointer) in temp.


Then traverse the temp pointer upto the specified position.

• After reaching the specified position, follow the steps given


below:
newnode -> left = temp;
newnode -> right = temp -> right;
temp -> right -> left = newnode;
temp -> right = newnode;
nodectr++;
Data Structure and Algorithms

The function cdll_insert_mid(), is used for inserting a node in the


intermediate position. Figure shows inserting a node into the circular double
linked list at a specified intermediate position other than beginning and end.

start
100 40 200
100
400
300 10 400 400 20 300

100 200

200 30 100

300

Figure Inserting a node at an intermediate position

Deleting a node at the beginning:

The following steps are followed, to delete a node at the beginning of the
list:

• If list is empty then display ‘Empty List’ message.

• If the list is not empty, follow the steps given below:

temp = start;
start = start -> right;
temp -> left -> right = start;
start -> left = temp -> left;

The function cdll_delete_beg(), is used for deleting the first node in the list.
Figure shows deleting a node at the beginning of a circular double linked
list.

start
200

300 10 200 300 20 300 200 30 200


100 200 300

Figure Deleting a node at beginning


Data Structure and Algorithms

Deleting a node at the end:

The following steps are followed to delete a node at the end of the list:

• If list is empty then display ‘Empty List’ message

• If the list is not empty, follow the steps given below:

temp = start;
while(temp -> right != start)
{
temp = temp -> right;
}
temp -> left -> right = temp -> right;
temp -> right -> left = temp -> left;

The function cdll_delete_last(), is used for deleting the last node in the list.
Figure shows deleting a node at the end of a circular double linked list.

start
100

200 10 200 100 20 100 200 30 100

100 200 300

Figure Deleting a node at the end

Deleting a node at Intermediate position:

The following steps are followed, to delete a node from an intermediate


position in the list (List must contain more than two node).

• If list is empty then display ‘Empty List’ message.

• If the list is not empty, follow the steps given below:

• Get the position of the node to delete.

• Ensure that the specified position is in between first node


and last node. If not, specified position is invalid.

• Then perform the following steps:


Data Structure and Algorithms

if (pos > 1 && pos < nodectr)


{
temp = start;
i = 1;
while (i < pos)
{
temp = temp->right;
i++;
}
temp->right->left = temp->left;
temp->left->right = temp->right;
free(temp);
printf("\n node deleted..");
nodectr--;
}

The function cdll_delete_mid(), is used for deleting the intermediate node


in the list.
Figure shows deleting a node at a specified intermediate position other than
beginning and end from a circular double linked list.
start
100

300 10 300 100 20 300 100 30 100

100 200 300

Figure Deleting a node at an intermediate position

Traversing a circular double linked list from left to right:

The following steps are followed, to traverse a list from left to right:

• If list is empty then display ‘Empty List’ message.

• If the list is not empty, follow the steps given below: temp = start;
Print temp -> data;
temp = temp -> right;
Data Structure and Algorithms

while(temp != start)
{
print temp -> data;
temp = temp -> right;
}

The function cdll_display_left _right(), is used for traversing from left to


right.

Traversing a circular double linked list from right to left:

The following steps are followed, to traverse a list from right to left:

• If list is empty then display ‘Empty List’ message.

• If the list is not empty, follow the steps given below:


temp = start;
do
{
temp = temp -> left;
print temp -> data;
} while(temp != start);

The function cdll_display_right_left(), is used for traversing from right to


left.

Source Code for Circular Double Linked List:


class Node {
int data;
Node prev;
Node next;

public Node(int data) {


this.data = data;
this.prev = null;
this.next = null;
}
}

class CircularDoublyLinkedList {
private Node head;
private Node tail;
Data Structure and Algorithms

public CircularDoublyLinkedList() {
head = null;
tail = null;
}

// Insertion at the beginning of the linked list


public void insertAtBeginning(int data) {
Node newNode = new Node(data);

if (head == null) {
head = newNode;
head.next = head;
head.prev = head;
tail = head;
} else {
newNode.next = head;
newNode.prev = tail;
head.prev = newNode;
tail.next = newNode;
head = newNode;
}
}

// Insertion at the end of the linked list


public void insertAtEnd(int data) {
Node newNode = new Node(data);

if (head == null) {
head = newNode;
head.next = head;
head.prev = head;
tail = head;
} else {
newNode.next = head;
newNode.prev = tail;
head.prev = newNode;
tail.next = newNode;
tail = newNode;
}
}

// Deletion of a node with given data


public void delete(int data) {
Data Structure and Algorithms

if (head == null) {
return;
}

if (head.data == data) {
if (head == tail) {
head = null;
tail = null;
} else {
head.next.prev = tail;
tail.next = head.next;
head = head.next;
}
return;
}

Node current = head;

while (current != tail && current.data != data) {


current = current.next;
}

if (current != tail) {
current.prev.next = current.next;
current.next.prev = current.prev;
}
}

// Display elements of the linked list in forward direction


public void displayForward() {
Node current = head;

if (current == null) {
System.out.println("Circular Doubly Linked List is
empty.");
return;
}

System.out.print("Circular Doubly Linked List (Forward): ");


do {
System.out.print(current.data + " <-> ");
current = current.next;
} while (current != head);
Data Structure and Algorithms

System.out.println(head.data + " (Head)");


}

// Display elements of the linked list in backward direction


public void displayBackward() {
Node current = tail;

if (current == null) {
System.out.println("Circular Doubly Linked List is
empty.");
return;
}

System.out.print("Circular Doubly Linked List (Backward):


");
do {
System.out.print(current.data + " <-> ");
current = current.prev;
} while (current != tail);

System.out.println(tail.data + " (Tail)");


}
}

public class CircularDoublyLinkedListExample {


public static void main(String[] args) {
CircularDoublyLinkedList list = new
CircularDoublyLinkedList();

list.insertAtEnd(1);
list.insertAtEnd(2);
list.insertAtBeginning(0);
list.insertAtEnd(3);

list.displayForward();
list.displayBackward();

list.delete(2);
System.out.println("Circular Doubly Linked List after
deleting 2:");
list.displayForward();
}
}
OUTPUT:-
Data Structure and Algorithms

Circular Doubly Linked List (Forward): 0 <-> 1 <-> 2 <-> 3 (Head)


Circular Doubly Linked List (Backward): 3 <-> 2 <-> 1 <-> 0 (Tail)
Circular Doubly Linked List after deleting 2:
Circular Doubly Linked List (Forward): 0 <-> 1 <-> 3 (Head)

➔Polynomials:

n
A polynomial is of the form: ∑ci x
i =0

Where, ci is the coefficient of the ith term and n is the degree of the
polynomial

Some examples are:

5x2 + 3x + 1
12x3 – 4x
5x4 – 8x3 + 2x2 + 4x1 + 9x0

It is not necessary to write terms of the polynomials in decreasing order of


degree. In other words the two polynomials 1 + x and x + 1 are equivalent.

The computer implementation requires implementing polynomials as a list


of pairs of coefficient and exponent. Each of these pairs will constitute a
structure, so a polynomial will be represented as a list of structures. A linked
list structure that represents polynomials 5x4 – 8x3 + 2x2 + 4x1 + 9x0
illustrates in figure 3.10.1.

start Exponent
Coefficient
500

5 4 100 -8 3 200 2 2 300 4 1 400 9 0 X


500 100 200 300 400

Figure 3.10.1. Single Linked List for the polynomial F(x) = 5x4 – 8x3 +
2x2 + 4x1 + 9x0
Data Structure and Algorithms

Source code for polynomial creation with help of linked


list:
class Term {
int coefficient;
int exponent;
Term next;

public Term(int coefficient, int exponent) {


this.coefficient = coefficient;
this.exponent = exponent;
this.next = null;
}
}

class Polynomial {
private Term head;

public Polynomial() {
head = null;
}

// Insert a new term at the end of the polynomial


public void insertTerm(int coefficient, int exponent) {
Term newTerm = new Term(coefficient, exponent);

if (head == null) {
head = newTerm;
} else {
Term current = head;
while (current.next != null) {
current = current.next;
}
current.next = newTerm;
}
}

// Display the polynomial


public void display() {
if (head == null) {
System.out.println("Polynomial is empty.");
return;
}
Data Structure and Algorithms

Term current = head;


while (current != null) {
System.out.print(current.coefficient + "x^" +
current.exponent);
current = current.next;
if (current != null) {
System.out.print(" + ");
}
}
System.out.println();
}
}

public class PolynomialCreationExample {


public static void main(String[] args) {
Polynomial poly = new Polynomial();
poly.insertTerm(3, 2);
poly.insertTerm(5, 1);
poly.insertTerm(7, 0);

System.out.println("Polynomial:");
poly.display();
}
}

OUTPUT:-

Polynomial:
3x^2 + 5x^1 + 7x^0

➔Addition of Polynomials:
To add two polynomials we need to scan them once. If we find terms with
the same exponent in the two polynomials, then we add the coefficients;
otherwise, we copy the term of larger exponent into the sum and go on.
When we reach at the end of one of the polynomial, then remaining part of
the other is copied into the sum.

To add two polynomials follow the following steps:

• Read two polynomials.


Data Structure and Algorithms

• Add them.
• Display the resultant polynomial.

Source code for polynomial addition with help of linked


list:
class Term {
int coefficient;
int exponent;
Term next;

public Term(int coefficient, int exponent) {


this.coefficient = coefficient;
this.exponent = exponent;
this.next = null;
}
}

class Polynomial {
private Term head;

public Polynomial() {
head = null;
}

// Insert a new term at the end of the polynomial


public void insertTerm(int coefficient, int exponent) {
Term newTerm = new Term(coefficient, exponent);

if (head == null) {
head = newTerm;
} else {
Term current = head;
while (current.next != null) {
current = current.next;
}
current.next = newTerm;
}
}

// Add two polynomials and store the result in a new polynomial


public Polynomial add(Polynomial other) {
Polynomial result = new Polynomial();
Data Structure and Algorithms

Term current1 = this.head;


Term current2 = other.head;

while (current1 != null && current2 != null) {


if (current1.exponent > current2.exponent) {
result.insertTerm(current1.coefficient,
current1.exponent);
current1 = current1.next;
} else if (current1.exponent < current2.exponent) {
result.insertTerm(current2.coefficient,
current2.exponent);
current2 = current2.next;
} else {
int sumCoefficients = current1.coefficient +
current2.coefficient;
if (sumCoefficients != 0) {
result.insertTerm(sumCoefficients,
current1.exponent);
}
current1 = current1.next;
current2 = current2.next;
}
}

// Append remaining terms from both polynomials


while (current1 != null) {
result.insertTerm(current1.coefficient,
current1.exponent);
current1 = current1.next;
}

while (current2 != null) {


result.insertTerm(current2.coefficient,
current2.exponent);
current2 = current2.next;
}

return result;
}

// Display the polynomial


public void display() {
if (head == null) {
System.out.println("Polynomial is empty.");
Data Structure and Algorithms

return;
}

Term current = head;


while (current != null) {
System.out.print(current.coefficient + "x^" +
current.exponent);
current = current.next;
if (current != null) {
System.out.print(" + ");
}
}
System.out.println();
}
}

public class PolynomialExample {


public static void main(String[] args) {
Polynomial poly1 = new Polynomial();
poly1.insertTerm(3, 2);
poly1.insertTerm(5, 1);
poly1.insertTerm(7, 0);

Polynomial poly2 = new Polynomial();


poly2.insertTerm(2, 3);
poly2.insertTerm(-5, 2);
poly2.insertTerm(4, 1);

System.out.println("Polynomial 1:");
poly1.display();

System.out.println("Polynomial 2:");
poly2.display();

Polynomial sum = poly1.add(poly2);


System.out.println("Sum of Polynomial 1 and Polynomial 2:");
sum.display();
}
}

©Topperworld
Data Structure and Algorithms

OUTPUT:-

Polynomial 1:
3x^2 + 5x^1 + 7x^0
Polynomial 2:
2x^3 + -5x^2 + 4x^1
Sum of Polynomial 1 and Polynomial 2:
2x^3 + 3x^2 + 9x^1 + 7x^0

You might also like