Array & Link List Data Structure
Array & Link List Data Structure
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.
➔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 :
• 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:
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.
➔Initialization of an Array
• Method 1:
• Method 2:
• 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
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.
➔Disadvantages of Arrays
➔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
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:-
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 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.
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.
• malloc()
• free()
➔malloc()
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 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.
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
Basically we can put linked lists into the following four items:
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
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.
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.
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.
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.
• Creation.
• Insertion.
• Deletion.
• Traversing.
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
• 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.
start
100
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:
The following steps are to be followed to insert a new node at the beginning
of the list:
• 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
5 100
500
void insert_at_beg()
{
node
*newnode;
newnode =
getnode();
if(start == NULL)
{
start = newnode;
}
else
{
newnode -> next = start;
start = newnode;
}
}
The following steps are followed to insert a new node at the end of the list:
Figure 6 shows inserting a node into the single linked list at the end.
start
100
50 X
500
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;
}
}
• After reaching the specified position, follow the steps given below:
prev -> next = newnode;
newnode -> next = temp;
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
50 300
500 new node
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.
The following steps are followed, to delete a node at the beginning of the
list:
start
200
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
");
}
}
The following steps are followed to delete a node at the end of the list:
start
100
10 200 20 300 30 X 40 X
100 200 300 400
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
start
100
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
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:
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");
}
}
}
The following code will count the number of nodes exist in the list using
recursion.
class LinkedList {
private Node head;
public LinkedList() {
head = null;
}
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
if (head.data == data) {
head = head.next;
return;
}
if (current != null) {
prev.next = current.next;
}
}
Data Structure and Algorithms
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
list.delete(2);
System.out.println("Linked List after deleting
2:");
list.display();
}
}
OUTPUT:-
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
start
400
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.
start
100 a
b
a 200 b 300 c X
100 200 300 c
Conceptual structure d
Implementation
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.
• Creation.
• Insertion.
• Deletion.
• Traversing.
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.
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.
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
• The left field of the new node is made to point the previous node.
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;
}
}
}
start
100
The following steps are to be followed to insert a new node at the beginning
of the list:
newnode=getnode();
start
400
X 40 100
400
The following steps are followed to insert a new node at the end of the list:
temp = start;
while(temp -> right != NULL)
temp = temp -> right;
temp -> right = newnode;
newnode -> left = temp;
Data Structure and Algorithms
start
100
300 40 X
400
• 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.
• After reaching the specified position, follow the steps given below:
start
100 40 200
100
400
400 20 300
X 10 400
200
100
200 30 X
300
The following steps are followed, to delete a node at the beginning of the
list:
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
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
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
{
temp = temp -> right;
i++;
}
temp -> right -> left = temp -> left;
temp -> left -> right = temp -> right;
free(temp);
printf("\n node deleted..");
}
start
100
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:
temp = start;
while(temp != NULL)
{
print temp -> data;
temp = temp -> right;
}
Data Structure and Algorithms
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.
temp = start;
while (temp->right != NULL)
temp = temp->right;
while (temp != NULL)
{
print temp->data;
temp = temp->left;
}
The following code will count the number of nodes exist in the list (using
recursion).
class Node {
int data;
Node prev;
Node next;
class DoublyLinkedList {
private Node head;
private Node tail;
public DoublyLinkedList() {
head = null;
tail = null;
}
if (head == null) {
head = newNode;
tail = newNode;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
}
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
}
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;
}
if (current != null) {
current.prev.next = current.next;
current.next.prev = current.prev;
}
}
list.insertAtEnd(1);
list.insertAtEnd(2);
list.insertAtBeginning(0);
list.insertAtEnd(3);
Data Structure and Algorithms
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:-
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.
start
100
• Creation.
• Insertion.
• Deletion.
• Traversing.
newnode = getnode();
start = newnode;
temp = start;
while (temp->next != NULL)
temp = temp->next;
temp->next = newnode;
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();
start = newnode;
newnode -> next = start;
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
5 100
500
The following steps are followed to insert a new node at the end of the list:
newnode = getnode();
start = newnode;
newnode -> next = start;
temp = start;
while(temp -> next != start)
temp = temp -> next;
temp -> next = newnode;
newnode -> next = start;
start
100
50 100
500
The following steps are followed, to delete a node at the beginning of the
list:
• 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
The following steps are followed to delete a node at the end of the list:
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
The following steps are followed, to traverse a list from left to right:
temp = start;
do
{
printf("%d ", temp -> data);
temp = temp -> next;
} while(temp != start);
Data Structure and Algorithms
class CircularSinglyLinkedList {
private Node head;
private Node tail;
public CircularSinglyLinkedList() {
head = null;
tail = null;
}
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
}
}
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;
}
}
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;
}
if (current != tail) {
prev.next = current.next;
}
}
if (current == null) {
Data Structure and Algorithms
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:-
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
• Creation.
• Insertion.
• Deletion.
• Traversing.
The following steps are to be followed to insert a new node at the beginning
of the list:
start
400
300 40 100
400
The following steps are followed to insert a new node at the end of the list:
start
100
300 40 100
400
• 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.
start
100 40 200
100
400
300 10 400 400 20 300
100 200
200 30 100
300
The following steps are followed, to delete a node at the beginning of the
list:
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
The following steps are followed to delete a node at the end of the list:
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
The following steps are followed, to traverse a list from left to right:
• 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 following steps are followed, to traverse a list from right to left:
class CircularDoublyLinkedList {
private Node head;
private Node tail;
Data Structure and Algorithms
public CircularDoublyLinkedList() {
head = null;
tail = null;
}
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;
}
}
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;
}
}
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;
}
if (current != tail) {
current.prev.next = current.next;
current.next.prev = current.prev;
}
}
if (current == null) {
System.out.println("Circular Doubly Linked List is
empty.");
return;
}
if (current == null) {
System.out.println("Circular Doubly Linked List is
empty.");
return;
}
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
➔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
5x2 + 3x + 1
12x3 – 4x
5x4 – 8x3 + 2x2 + 4x1 + 9x0
start Exponent
Coefficient
500
Figure 3.10.1. Single Linked List for the polynomial F(x) = 5x4 – 8x3 +
2x2 + 4x1 + 9x0
Data Structure and Algorithms
class Polynomial {
private Term head;
public Polynomial() {
head = null;
}
if (head == null) {
head = newTerm;
} else {
Term current = head;
while (current.next != null) {
current = current.next;
}
current.next = newTerm;
}
}
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.
• Add them.
• Display the resultant polynomial.
class Polynomial {
private Term head;
public Polynomial() {
head = null;
}
if (head == null) {
head = newTerm;
} else {
Term current = head;
while (current.next != null) {
current = current.next;
}
current.next = newTerm;
}
}
return result;
}
return;
}
System.out.println("Polynomial 1:");
poly1.display();
System.out.println("Polynomial 2:");
poly2.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