Write a java program to
a) Input marks of 10 students marks into a doubly linked list.
b) Output marks in the doubly linked list according to the input order.
c) Output marks in the doubly linked list according to the reverse order.
import java.util.Scanner;
public class DoublyLinkedList
{
//define Node for Linked list
class Node
{
int data;
Node previous;
Node next;
public Node(int data)
{
this.data = data;
}
}
Node head, tail = null;
//add element to linked list(double)
public void addNode(int data)
{
Node newNode = new Node(data);
if(head == null)
{
head = newNode;
tail = newNode;
head.previous = null;
tail.next = null;
}
else
{
tail.next = newNode;
newNode.previous = tail;
tail = newNode;
tail.next = null;
}
}
//method to print all element from head
public void display()
{
Node current = head;
if(head == null)
{
System.out.println("List is empty");
return;
}
System.out.println("doubly linked list from head");
while(current != null)
{
System.out.print(current.data + " ");
current = current.next;
}
}
//method to print all element from tail
public void displayReverse()
{
Node current = tail;
if( tail == null)
{
System.out.println("List is empty");
return;
}
System.out.println("Linked list Reverse order: ");
while(current != null)
{
System.out.print(current.data + " ");
current = current.previous;
}
}
//main method
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
int i;
DoublyLinkedList dList = new DoublyLinkedList();
//Add module marks of 10 student to linked list
for (i=0; i < 10; i++)
{
System.out.println("Enter a Module marks of a Student?");
int mark = Integer.parseInt(myObj.nextLine());
dList.addNode(mark);
}
//Displays the all students mark from head
dList.display();
System.out.println();
//Displays all student marks from tail(Reverse)
dList.displayReverse();
}
}
No comments:
Post a Comment