You are on page 1of 10

DATA STRUCTURES AND ALGORITHMS LAB

TOPIC: DOUBLY LINKED LIST

NAME: SYED AMANULLAH WASTI

REGISTRATION ID: cs211099

SECTION: 3D2

Q1. Implement two way search on doubly linked list.

CODE:

import java.util.Scanner;

class Node{

int data;

Node next;

Node prev;

Node(int data)

this.data = data;

this.next = null;

this.prev = null;

class DLL{
Node head;

Node tail;

DLL()

head = null;

tail = null;

public void insert(int data){

Node n = new Node(data);

if(head == null){

head = n;

tail = n;

else{

tail.next = n;

n.prev = tail;

tail = n;

public void print(){


Node cur = tail;

System.out.print("\n\nElements : ");

while(cur!=null){

System.out.print(cur.data+",");

cur = cur.prev;

public int Search(int dvalue){

Node i = head;

Node j = tail;

while(i.next!=null)

if(j.data == dvalue || i.data == dvalue){

return 1;

else{

i=i.next;

j=j.prev;

return 0;
}

public class Main{

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

DLL a = new DLL();

a.insert(66);

a.insert(55);

a.insert(44);

a.insert(33);

a.insert(22);

a.insert(11);

a.print();

System.out.print("\n\nEnter the element to search : ");

int element = in.nextInt();

int found = a.Search(element);

if(found == 1)

System.out.print("\nElement found.");

}else

System.out.print("\nElement not found.");


}

OUTPUT:

Test 1:

Test 2:

Q2. Implement method to join 2 doubly linked list.

CODE:

import java.util.Scanner;

class Node{

int data;

Node next;

Node prev;

Node(int data)
{

this.data = data;

this.next = null;

this.prev = null;

class DLL{

Node head;

Node tail;

DLL()

head = null;

tail = null;

public void insert(int data){

Node n = new Node(data);

if(head == null)

head = n;

tail = n;

}
else{

tail.next = n;

n.prev = tail;

tail = n;

public void print(){

Node cur = head;

while(cur!=null)

System.out.print(cur.data+",");

cur = cur.next;

public DLL Combine(DLL a, DLL a1){

DLL a2 = new DLL();

Node i = a.head;

Node j = a1.head;

while(i != null)

{
a2.insert(i.data);

i = i.next;

while(j != null)

a2.insert(j.data);

j=j.next;

return a2;

public class Main{

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

DLL a = new DLL();

DLL a1 = new DLL();

System.out.print("Enter the numbers of nodes to make First Linked list : ");

int n = in.nextInt();

for(int i = 1; i < n+1; i++)

System.out.print("Enter Data "+i+" : ");


int element = in.nextInt();

a.insert(element);

System.out.println("\nFirst Linked List");

a.print();

System.out.print("\n\nEnter the numbers of nodes to make Second Linked list : ");

n = in.nextInt();

for(int i = 1; i < n+1; i++)

System.out.print("Enter Data "+i+" : ");

int element = in.nextInt();

a1.insert(element);

System.out.println("\nSecond Linked List");

a1.print();

DLL a2 = new DLL();

a2 = a2.Combine(a,a1);

System.out.println("\n\nAfter Combining the both Linked List");

a2.print();

}
}

OUTPUT:

You might also like