Professional Documents
Culture Documents
LAB 8
OBJECT:
Lab Task
Write a program that can insert the records of employees in a link list. The record includes
employees’ name, designation, department and company name.
a. The program should be able to insert the record as first, last and as middle node in
the list.
b. The program should be able to search any record.
SOURCE CODE:
class Link {
String item;
Link previous;
Link next;
public Link(String item) {
this.item = item;
}
}
Link head, tail = null;
public void addNode(String data) {
Link newLink = new Link(data);
if(head == null) {
head = tail = newLink;
head.previous = null;
tail.next = null;
}
else {
tail.next = newLink;
newLink.previous = tail;
tail = newLink;
tail.next = null;
}
}
public void insertAt(int index, String data){
int counter = 0;
Link newLink = new Link(data);
Link link = head;
if(head == null){
head = newLink;
tail = newLink;
return;
}
while(counter<index-1){
link = link.next;
counter++;
}
Link temp = link.next;
link.next = newLink;
link.next.next = temp;
}
public void print() {
Link current = head;
if(head == null) {
System.out.println("Doubly linked list is empty");
return;
}
while(current != null) {
System.out.print(current.item + " ");
current = current.next;
}
}
OUTPUT:
Home Task
SOURCE CODE:
head = newLink;
tail = newLink;
return;
}
while (counter < index - 1) {
link = link.next;
counter++;
}
Link temp = link.next;
link.next = newLink;
link.next.next = temp;
}
public void print() {
Link current = head;
if (head == null) {
System.out.println("Doubly linked list is empty");
return;
}
System.out.println("Nodes of doubly linked list: ");
while (current != null) {
System.out.print(current.item + " ");
current = current.next;
}
}
public void search(int data) {
if (head == null) {
System.out.println("List is empty.");
return;
}
int counter = 0;
Link link = head;
int pos = -1;
while (link != null && pos == -1) {
if (data == link.item) {
pos = counter + 1;
break;
}
link = link.next;
counter++;
}
if (pos != -1) {
System.out.println(data + " Found at position: " + pos);
} else {
System.out.println("Item not Found!");
}
}
}
}
OUTPUT: