You are on page 1of 4

DOUBLE LINKED LIST TASK

Task: Write a program to insert the records of students in a Doubly


linked list and insert elements at last node.
Code:
import java.util.Scanner;

class Student {
String name;
int id;
Student next;
Student prev;

public Student(String name, int id) {


this.name = name;
this.id = id;
this.next = null;
this.prev = null;
}
}

class DoublyLinkedList {
Student head;
Student tail;

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

public void insertAtEnd(Student newStudent) {


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

public void printList() {


Student current = this.head;
while (current != null) {
System.out.println(current.name + " " + current.id);
current = current.next;
}
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of students:");
int numStudents = scanner.nextInt();

DoublyLinkedList list = new DoublyLinkedList();

for (int i = 0; i < numStudents; i++) {


System.out.println("Enter the name and ID of student " + (i+1) +
":");
String name = scanner.next();
int id = scanner.nextInt();

Student newStudent = new Student(name, id);


list.insertAtEnd(newStudent);
}
System.out.println("Student records:");
list.printList();
}
}
Output:

You might also like