Friday, February 4, 2022

Display linkedlist

 


import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Display_A_LinkedList {
public static class Node {
int data;
Node next;
}

public static class LinkedList {
Node head;
Node tail;
int size;

void addLast(int val) {
Node temp = new Node();
temp.data = val;
temp.next = null;

if (size == 0) {
head = tail = temp;
} else {
tail.next = temp;
tail = temp;
}

size++;
}

public int size() {
// write code here
return size;
}


// write code here
public void display() {
Node temp = head;

while (temp != null) {
System.out.print(temp.data + "\t");
temp = temp.next;
}
System.out.println();
}

}

public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
LinkedList list = new LinkedList();

String str = br.readLine();
while (str.equals("quit") == false) {
if (str.startsWith("addLast")) {
int val = Integer.parseInt(str.split(" ")[1]);
list.addLast(val);
} else if (str.startsWith("size")) {
System.out.println(list.size());
} else if (str.startsWith("display")) {
list.display();
}
str = br.readLine();
}
}
}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...