You are on page 1of 23

Data Structures Using Java UNIT-I II Year IV Semester B.

Sc

CONCEPT OF ABSTRACT DATA TYPES (ADTs)

Abstract Data Type:


Abstract data types or ADTs are a mathematical specification of a set of data and the
set of operations that can be performed on the data. They are abstract in the sense that the
focus is on the definitions of the constructor that returns an abstract handle that represents the
data, and the various operations with their arguments. The actual implementation is not
defined, and does not affect the use of the ADT. An ADT consists of two parts:

 Declaration of Data
 Declaration of Operations

For example, students of a college can be characterized with many properties such
as,

(1) Roll Number


(2) Student Name
(3) Marks in different subjects
(4) Sex
(5) Age and so on.

There may be different possible operations which can be performed on these properties of
the students. For example we can display the information, edit the information, print the sheet
of the students and so on. So the ADT “Student” is defined as follows

ADT Student
{
Data :
Roll_Number;
Student_Name;
Marks_in_different_subjects;
Sex;
Age;

Operations:
Read_information();
Display_information();
Print_mark_Sheet();
}

Department of Computer Science 1 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

When realized in a computer program, the ADT is represented by an interface, which shields
a corresponding implementation. Users of an ADT are concerned with the interface, but not
the implementation, as the implementation can change in the future. ADTs typically seen in
textbooks and implemented in programming languages (or their libraries) include:

• String ADT
• List ADT
• Stack (last-in, first-out) ADT
• Queue (first-in, first-out) ADT
• Binary Search Tree ADT
• Priority Queue ADT
• Complex Number ADT (imaginary numbers)

There is a distinction, although sometimes subtle, between the abstract data type and
the data structure used in its implementation. For example, a List ADT can be represented
using an array-based implementation or a linked-list implementation. A List is an abstract
data type with well-defined operations (add element, remove element, etc.) while a linked-list
is a pointer-based data structure that can be used to create a representation of a List. The
linked-list implementation is so commonly used to represent a List ADT that the terms are
interchanged and understood in common use.

Similarly, a Binary Search Tree ADT can be represented in several ways: binary
tree, AVL tree, red-black tree, array, etc. Regardless of the implementation, the Binary
Search Tree always has the same operations (insert, remove, find, etc.)

Data Type:
Data type is way to classify various types of data such as integer, string etc. which
determines the values that can be used with the corresponding type of data, the type of
operations that can be performed on the corresponding type of data. Data type of two types

 Built-in Data Type


 Derived Data Type
Built-in Data Type:
Those data types for which a language has built-in support are known as Built-in Data types.
For example, most of the languages provides following built-in data types.
 Integers
 Boolean (true, false)
 Floating (Decimal numbers)
 Character and Strings

Derived Data Type:


Those data types which are implementation independent as they can be implemented in one
or other way are known as derived data types. These data types are normally built by
combination of primary or built-in data types and associated operations on them. For
example −

Department of Computer Science 2 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

 List
 Array
 Stack
 Queue

File Structures:
A file is a collection of data stored on mass storage (e.g., disk or tape). Following are
the reasons to store data on mass storage

 Too big to fit in main memory


 Share data between programs
 Backup (disks and tapes are less volatile than main memory)

The data is subdivided into records (e.g., student information).


Each record contains a number of fields (e.g., name, GPA).
One (or more) field is the key field (e.g., name).

To provide convenient access for the user we can organize the records on the mass
storage. Following are different ways to access the records in the files

 Sequential files
 Indexed files
 Hashed files.

Sequential Files: Sequential Files Records are conceptually organized in a sequential list and
can only be accessed sequentially. The actual storage might or might not be sequential.
Usually on a tape the records are stored sequentially, but on a disk, it might be distributed
across sectors and the operating system would use a linked list of sectors to provide the
illusion of sequential behavior. This is not a convenient organization for accessing a
particular record quickly. Sequential search is even slower on disk/tape than in main memory

Indexed Files: An index for a file is a list of key field values occurring in the file along with
the address of the corresponding record in the mass storage. Typically the key field is much
smaller than the entire record, so the index will fit in main memory. The index can be
organized as a list, a search tree, a hash table, etc. To find a particular record,

 Search the index for the desired key.


 When the search returns the index entry, extract the record’s address on mass storage.
 Access the mass storage at the given address to get the desired record.

Multiple indexes, one per key field, allow searches based on different fields.

Hashed Files: In this method of file organization, hash function is used to calculate the
address of the block to store the records. The hash function can be any simple or complex
mathematical function. The hash function is applied on some columns/attributes – either key
or non-key columns to get the block address. Hence each record is stored randomly

Department of Computer Science 3 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

irrespective of the order they come. Hence this method is also known as Direct or Random
file organization. If the hash function is generated on key column, then that column is called
hash key, and if hash function is generated on non-key column, then the column is hash
column.
When a record has to be retrieved, based on the hash key column, the address is
generated and directly from that address whole record is retrieved. Here no effort to traverse
through whole file. Similarly when a new record has to be inserted, the address is generated
by hash key and record is directly inserted. Same is the case with update and delete. There is
no effort for searching the entire file or sorting the files. Each record will be stored randomly
in the memory. These types of file organizations are useful in online transaction systems,
where retrieval or insertion/updating should be faster.

Primitive Data Structures: Data structures that normally are directly operated upon by
machine-level instructions are known as primitive data structures. The integers, real, logical
data, character data, pointer and reference are primitive data structures.

Non-primitive Data Structures: These are more complex data structures. These data
structures are derived from the primitive data structures. They stress on formation of sets of
homogeneous and heterogeneous data elements. The different operations that are to be
carried out on data are nothing but designing of data structures. The various operations that
can be performed on data structures

 CREATE
 DESTROY
 SELECT
 UPDATE

Data Structure:
Data structure is a collection of data elements organized in a specified manner and
operations on data elements.
Classification of Data Structures:
These data structures can be divided into two categories.

1. Linear data structures.


2. Non-linear data structures.

1. Linear data structures: In linear data structures, data is stored in linear form.
Ex: linked list, stack, and queue.

2. Non-linear data structures: In non-linear data structures, data is stored in non-linear


form.
Ex: trees, graphs.

Department of Computer Science 4 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

Linear Lists - ADT:


Linear ordering of atoms/terms is the essential property of linear list. List nothing
more than a set of terms organized sequentially. Hence a list is a sequence of zero or more
elements of a given type, the form of list is,

L=(a1,a2,a3,……an) (n≥0). Linear list is a data object whose instances are of the form
(a1,a2,a3,……an) where, ai is element of list.
n denotes number of elements in the list
a1 is the first element of the list
an is the last element of the list
n=0 means empty list.
Elements can be linearly ordered according to their position in the list. We say a i precedes ai+1
( ai+1 follows ai ) and ai is at position i.
An array is an example of list. In an array, the sequential organization is provided
implicitly by its index.

Examples:

(1) Student names order by their alphabets.


(2) A list of exam scores sorted by descending order.
Days of Week = (S, M, T, W, Th, F, Sa)
Months = (Jan, Feb, Mar, Apr, …, Nov, Dec)

AbstractDataType LinearList
{
Instances : Ordered finite collection of zero or more elements.
Operations :
Create(): Create an empty linear list
Destroy: Erase the list
IsEmpty(): Return true if the list is empty. False Otherwise
Length(): Return the number of elements in the list
Search(X): Return the position of x in the list, return 0 if it is not in the list
Delete(k,x): Delete the kth element and return it in x, function returns the
modified list.
Insert(k,x): Insert x just after the kth element, function returns the modified
linear list.
Output(out): put the list into the output stream out.
}

The ADT List is a linear sequence of an arbitrary number of items, together with the
following access procedures:

Department of Computer Science 5 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

Procedure Name Description


createList( ) Create an empty list
add(index, item) Insert item at position index of a list if 1<=index<= size()+1.
If index <= size(), items at position index onwards are shifted one
position to the right
isEmpty( ) Determine if a list is empty
size( ) Returns number of items in a list
remove(index) Remove item at position index of a list if 1<=index<= size().
Items at position index+1 onwards are shifted one position to the left
get(index) Returns item at position index of a list if 1<=index<=size()

Think about a list that you might encounter, such as a list of important dates, a list of
addresses or a grocery list. Assuming that it is a neat one-column list, the items on the list
appear in a sequence. The list has one first element (the head) and one last element. Except
for the first and the last, each element has one unique predecessor and one unique successor.
So we can say that a list is a linear sequence of a number of items. The items in a list have
also to be of the same type.
We can implement linear list in two ways

 Array
 Linked List

Linear List implementation using Arrays:

We can implement a list using simple arrays concept. We can store any data in the
list. As we are suing the array to create the list we have to declare the array with relevant type
of data, which is storing in it. For Example, List of Students that are having their total
percentage above 70. For this we have to maintain their names so we need to declare String
array in this context.

Creation of linear list using arrays:

We need to declare an array with desired size and read the elements in that array. This
task can be achieve by using createList(). This method will create a list with given size and it
also assigns the items to that list also.

Adding an item at given index in the linear list using arrays:

To add an item to the list, we will define add(index,item). This method first declares
a new array with the size as the size of already existing array and additional one location to
store new item in the list. So we can define the new size like this,

newArraySize = existedArraySize + 1;

Now declare a new list with size newArraySize. After that, copy the all items to the
new list from existed list up to given index. When we reached index position we have to
insert the item there. After that the remaining items in the original list should be copied to

Department of Computer Science 6 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

new list up to the last item in the original array. Now the new list will contain all the items
including new item also. Now we have to copy all these items to original list. But, before that
we have to change size of the original list. So first change size of the original list to
newArraySize then assign the items from new list to original list. This ends adding item to
list at given index.

Knowing size of the list using arrays:

To know the size of the list we can use the length property. As we are implementing
lists using arrays we can access the length property of array type as size of the list.

Removing item from the list at given index using arrays:

To remove we will define a method called remove(index). By using this method we


can remove the item from the list. After deletion we have to update size of the list also. i.e.,
we have to reduce the size of the list. Here we have a problem that if we decreased the size
the last item will lose. So after arranging the list items only we have to reduce the size of the
list.
For Example, if we have a list contains 5 items and we want to remove item at index
2. Then we have to adjust items after given index to its previous index like item at 3 to item
at 2, and item at 4 to item at 3. Then only we have to reduce the size of the list.

Retrieving item at the given index using arrays:

To retrieve the item at the given index we will use the get(index). This method will
get the item at the given location as we will getting element at given location in the array.

Advantages:

 Array stores items in consecutive memory locations.


 Arrays have better cache locality which increases the performance.
Disadvantages:

o Array size is fixed once we declared.


o Inserting and deleting operations are very expensive due to elements shifting
in both the cases.

Aim: Write a java program to implement list using arrays


import java.util.*;
class ArrayList
{
int a[],size;
Scanner sc=new Scanner(System.in);
public void createList()
{
System.out.println("Enter the size of the list:");
size=sc.nextInt();

Department of Computer Science 7 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

a=new int[size];
System.out.println("Enter elements in the list:");
for(int i=0;i<size;i++)
a[i]=sc.nextInt();
System.out.println("List Created.");
}

public void add(int index, int ele)


{
int i=0,j=0,newSize;
newSize=a.length+1;
int b[]=new int[newSize];
if(index<=a.length-1)
{
while(i<size)
{
while(j<a.length)
{
if(i==index)
{
b[i]=ele;
i++;
}
else
{
b[i]=a[j];
j++;
i++;
}
}
}
a=new int[newSize];
for(i=0;i<newSize;i++)
a[i]=b[i];
}
else
System.out.println("Invalid index");
}

public void removeItem(int index)


{
int i=0,j=0,newSize;
newSize=a.length-1;
int b[]=new int[newSize];
if(index>=0 && index<a.length)
{
for(j=0,i=0;j<newSize && i<a.length;)
{

Department of Computer Science 8 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

if(i!=index)
{
b[j]=a[i];
i++;
j++;
}
else
{
i++;
}
}
a=new int[newSize];
for(i=0;i<newSize;i++)
a[i]=b[i];
}
else
{
System.out.println("Invalid index");
}
}

public int size()


{
return size;
}

public int getItem(int index)


{
if(index>=0 && index<a.length)
return a[index];
else
{
System.out.println("Invalid Index");
return 0;
}
}

public void dispList()


{
System.out.print("The Items in the list are: ");
System.out.println(Arrays.toString(a));
}

class ArrayListDemo
{
public static void main(String args[])

Department of Computer Science 9 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

{
Scanner sc=new Scanner(System.in);
ArrayList al=new ArrayList();
al.createList();
int l=al.size();
System.out.println("The Size of the list is: " +l);
al.dispList();
System.out.println("Enter an item to add to the list:");
int item=sc.nextInt();
System.out.println("Enter where to add the element in list:");
int pos=sc.nextInt();
al.add(pos,item);
System.out.print("After adding item, ");
al.dispList();
System.out.println("Enter index of an item in list to find the item at the index:
");
pos=sc.nextInt();
System.out.println("The Item at location "+pos+" is : "+al.getItem(pos));
System.out.println("Enter index of an item to remove from list:");
pos=sc.nextInt();
al.removeItem(pos);
System.out.print("After removing item, ");
al.dispList();
}
}

Linear List implementation using Linked Lists:

We can implement a list using linked list concept. We have some complexities while
using array to create lists like its size and while update the list. To overcome those problems
we can use linked lists. A Linked List is a combination of nodes, where each node is
connected with next node in the list and starting node address is stored as Root. But all these
nodes are not stored sequentially like arrays. A Node contains two parts one is data item and
another one is address part which stores the address of the next node in the list as shown
below.

Node Data Item Address of next Node

And, a simple linked list with 3 items 10, 20, 30 will be represented as shown below
Root

10 20 30

Where, Root is the address of stating node.


Creation of linear list using linked list:

Department of Computer Science 10 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

We can create the list by using createList(). This method will create a list with given
size and it also assigns the items to that list also. But here size is not fixed. We can change the
size of the list at any time. In this method every time we will create a new node and will be
linked with the list at specified position.

Adding an item at given position in the linear list using linked list:

To add an item to the list, we will define add(loacation,item). In this method we will
update the links between the nodes in such a way that the new node will come at desired
place in the list.

Knowing size of the list using linked list:

To know the size of the list we don’t have the length property in linked list as we used
in arrays. So the only way is we have to traverse the list starting from root node to last and
count the number of nodes in the list. The size of the list is the number of nodes in the list
(except Root node).

Removing item from the list at given index using linked list:

To remove we will define a method called remove(item). By using this method we


can remove the item from the list. After deletion we have to update the links between the
nods. Here we have a problem that if we updated the links we will lose some item(s) in the
list. So after changing the links between the nodes only we will remove the item.

For Example, if we have a list contains 5 items and we want to remove item 3. Then
we have to adjust link from item 2 to item 3 to item 2 to item 4. Then automatically item 3
will be out of the list.

Arrays ADT

We generally used the variables to store the values. It can be represented as shown
below in memory.

Code : int i=10; action in memory: 10

i
This is in case of normal variables. But in the case of reference variables it will
be little bit different, as shown below.
e
Code: Emp e=new Emp(); action in memory: 536272H 536272H

e.eno=10; eno 10
If we create a variable to a primitive type then it is called value variable. If we
create a variable to array or class then it is called as reference variable. In Simple

Department of Computer Science 11 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

words array will refer to several values of same type. Length field holds allocated
number of elements. Elements indexed from 0 to length-1

We already worked with arrays. Now we will show that array is an ADT.
That means we will show some operations on arrays. We have Arrays class in
java.util package. And we have some static methods like equals(), fill(), sort() and
toString() etc.,

equals() method will take two arrays and compare that two arrays and return
the result as true if both are same false otherwise. fill() takes two arguments one is
array and another one is element to be placed. sort() will take an array as argument
and sorts the given array in ascending order. toString() will take no argument and
display the elements of array in array format.

Aim: Write a java application to explain array ADT.

import java.io.*;
import java.util.*;

class ArrayADTDemo
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter size of the array:");
int size=Integer.parseInt(br.readLine());
int x[]=new int[size];
System.out.print("After filling with 8. Elements of the array are:");
Arrays.fill(x,8);
System.out.println(Arrays.toString(x));
System.out.println("Enter Elements of the array:");
for(int i=0;i<size;i++)
x[i]=Integer.parseInt(br.readLine());
System.out.print("Elements of the array:");
System.out.println(Arrays.toString(x));
System.out.print("After sorting elements of the array are:");
Arrays.sort(x);
System.out.println(Arrays.toString(x));
}
}

Linked Lists

Department of Computer Science 12 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

A list is a set of similar data components. A list whose components are linked
together by means of a pointer (reference) is referred to as linked list. In linked list, each
individual component within the list includes a pointer which indicates the address of the next
component in the list. Therefore, the relative order of the components can easily be changed
by simply altering the pointers. Individual components can easily be added to (or) deleted
from the list by altering the pointers.

Linked Lists are used in the construction of compilers, operating system, and data
base management systems etc. Linked list can be constructed in different forms.
1. Single Linked List (or) Linear Linked List.
2. Double Linked List.
3. Circular Linked List.

1. Single Linked List (or) Linear Linked List: following figure shows a single linked
list

root root ( address of the first element in the list)

10 20 30 40 50 null
Every element in the list consists of two items an integer and pointer references to the
next component within the list. Generally the address of the first component in the list will be
maintained in a separate variable. A pointer field of the last component will be assigned with
a special type value called null. Inserting or deleting new components to the list will be done
by simply adjusting the pointers.

Different kinds of operation can be performed with linked list, like creating a linked
list, deleting a element from a linked list, inserting a element into linked list, searching for a
particular element in a linked list.

Creation of Single Linked List:

1. Compose the node structure of the Linked List.

Ex: class node


{
int a;
node next;
}

2. Create first node and keep the address of the first node in separate variable say root.
root

Ex: 10 NULL

3. Create new node and link it to previous node.

Department of Computer Science 13 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

4. Repeat step no. 3 until required no. of nodes are linked.

Ex: root

10 20 30 40 50 NULL

first element last element

5. Keep address field of last node as NULL.

Inserting an element in to a single linked list :

An additional component can easily be inserted into some designated location within
an existing linked list. To insert a component, a new component must be created
dynamically, determine its intended location within the list, and then adjust a few pointers.
An element can be inserted
1. insert node at first
2. insert node at middle
3. insert node at last
1. Inserting node at first position : Consider the following existing linked list

(root)

10 20 30 40 50 NULL

1) integer
25 NULL node structure int pointer 2) pointer

n
‘root’ is a variable which holds the address of the first element in the linked list. Each
element consists of data and address field.
If a new element with data value 25 is to be inserted at the top.
i) Create a new element and assume new element address is ‘n’.
ii) Move the address in root to the address field of new element.
iii) Move the address of new element to root .
n.next = root;
root = n;
After insertion the linked list will be as shown below.

(root)

Department of Computer Science 14 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

25 10 20 30 40 50 NULL

new element

2. Inserting an element after a particular element :


Consider the following existing linked list.

(root)

10 20 30 40 50 NULL
35 NULL
p node structure
n int pointer

‘root’ holds the address of first element. To insert an element after element.
i) create a new element and assume new element address is ‘n’.
ii) starting from first element process the linked list until desired element, after which
a new element is to be inserted, is found. Say the address of that element is ‘p’.
Ex: Inserting after element 30 i.e., p has address of element 30.
iii) Move the address of element 40, which is in address field of 30 to address field of
new element.
iv) Move the address of new element ‘n’ to address field of element 30.
n.next = p.next;
p.next = n;
After insertion linked list will be

(root)

10 20 30 35 40 50
NULL
inserted element

Deleting an element from the Linked List :

To delete an element from the existing linked list, find the address of the element to
delete, adjust the pointers which deleted the element from the list.

1. To delete an element at first :Consider the following linked list

(root)

Department of Computer Science 15 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

10 20 30 40 50 NULL

The element structure is : int pointer

a next
‘a’ is integer variable.
‘next’ is pointer variable.

where root holds address of first element.

i) move the address of the first element to temp variable ‘p’.


ii) move address of 2nd element to root.
p=root;
root=root.next;

Linked List after deletion :

(root)

20 30 40 50 NULL

10

2. to delete a particular element : Consider the following linked list.

(root)

10 20 30 40 50 NULL

q p

where root holds address of the first element. ‘p’ holds address of the element which is to be
deleted ‘q’ holds address of element before p.

i) Find the address of the element to be deleted, by processing the list from
beginning. Say address of the element is ‘p’. And ‘q’ is the address of the
element which is before ‘p’ element.

Department of Computer Science 16 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

ii) Move address of element ‘40’ to q address field.


iii) Delete the element using delete(p) operator.

q.next=p.next;

linked list after deletion :

(root)

10 20 30 40 50 NULL

q p

Double Linked Lists

A Double Linked List is a list in which each component in the linked list have two
pointers which can point to both the next element and the previous element. The concept of
double linked list is as shown in figure below.
head data value tail

lptr rptr
NULL 10 20 30 40 NULL

Each component in the double linked list has the following structure.
data value
lptr rptr

20

pointer points to the pointer points to the


previous element in the list next element in the list

The main advantage of double linked list is that it permit traversing and searching of
the list in both directions. For a given pointer to any list element, it is possible to get to any
other element in the list. To move to the end of the list, simply follow the next pointers and
to move to the beginning of the list, simply follow the previous pointers.

Department of Computer Science 17 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

When compared to single linked list, the extra pointers in double linked list occupies
additional space and also increases the maintenance of the insertion and deletion because
there are more pointers to adjust.

Creation of Double Linked List :

1. Compose the mode structure of the double linked list.

Ex: class node


{
int a;
node lptr;
node rptr;
}
2. Create first node and keep the address of first node in separate variable say head.
head
Ex:

NULL 10 NULL

3. Create new node and link new node and previous nodes bidirectionally.

4. Repeat step 3, until required no. of nodes are linked. Keep the address of the last node in a
separate variable say tail.

Ex:
head tail

NULL 10 20 30 NULL

5. Keep left pointer of first node and right pointer of last node as NULL.

Inserting an element into Double Linked List :

An element can be inserted into a existing double linked list at any desired position.

1. To insert element as first element :

Department of Computer Science 18 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

head data value tail


lptr rptr
NULL 10 20 30 40 NULL

NULL 10 NULL

n
Node Structure
reference int reference
lptr a rptr

a  integer variable
lptr, rptr  reference variables

head holds address of first element.


tail holds address of last element.
1. Create a new element and assume ‘n’ holds address of new element.
2. Move address in head to right pointer of new element.
3. Move the address of new element to left pointer of first element.
4. Move address of new element to ‘head’.

n.rptr = head;
head.lptr = n;
head = n;

Linked list after insertion :


head tail

NULL 5 10 20 30 40 NULL

inserted element

2. To insert element as last element :

Department of Computer Science 19 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

Consider the following linked list.


head tail

NULL 10 20 30 NULL

NULL 10 NULL

n
1. Create a new element and assume ‘n’ holds address of new element.
2. Move address in ‘tail’ to left pointer of new element.
3. Move address of new element to right pointer of last element.
4. Move address of new element to tail.
n.lptr = tail;
tail.rptr = n;
tail = n;
Linked List after Insertion
head tail

NULL 10 20 30 35 NULL

inserted element

Inserting element between two elements (or) after a particular element :

Consider the following linked list.


head tail

NULL 10 20 30 NULL

p
NULL 35 NULL

n
1. Create a new element and assume ‘n’ holds address of new element.
2. Find address of the element, after which new element is to be inserted. Ex: after element
20. ‘p’ holds address of element ‘20’.
3. Move address of element ‘20’ to left pointer of new element.

Department of Computer Science 20 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

4. Move address of element ‘30’ to right pointer of new element.


5. Move address of new element to left pointer of 30.
6. Move address of new element to right pointer of 20.

n.lptr = p;
n.rptr = p.rptr;
p.rptr.lptr = n;
p.rptr = n;

Linked list after insertion :


Linked List after Insertion is
head tail

NULL 10 20 25 30 NULL

inserted element

Deleting an element from Double Linked List :

Any element can be deleted from the double linked list by knowing the address of the
element.

1. To delete first element : Consider the following double linked list


head tail

NULL 10 20 30 NULL

P element to be deleted node structure :


lptr a rptr

1. Move the address of first element to variable ‘p’.


2. Move address of second element to head.
3. Move NULL to left pointer of new first element.

p = head;
head = head.rptr;
head.lptr =null;

Linked List after Deletion :

Department of Computer Science 21 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

head tail

NULL 20 30 NULL

2. To delete last element : Consider the following linked list


head tail

NULL 10 20 30 NULL

1. Move last element address to variable p.


2. Move second last element address to tail.
3. Move NULL to right pointer of new last element.

p = tail;
tail = tail.lptr;
tail.rptr = NULL;
Linked List after deletion :

head tail

NULL 10 20 NULL

3. To delete a particular element : Consider the following linked list

head tail
NULL 10 20 30 NULL

1. Find the element to delete by processing list either from head (or) from tail Assume ‘p’
holds address of element to be deleted.
Ex: Element to be deleted is ’20’ . ‘p’ holds address of 20.

2. Move address of ‘30’ to right pointer of ‘10’.


3. Move address of ‘10’ to left pointer of ‘30’.
p.rptr.lptr = p.lptr;
p.lptr.rptr = p.rptr;

Department of Computer Science 22 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-I II Year IV Semester B.Sc

Linked list of deletion :

head tail

NULL 10 30

Department of Computer Science 23 A.S.N. Degree College, Tenali

You might also like