Friday, February 4, 2022

Add Last In LinkedList

 

Example: Let us dry run the algorithm using a few addLast operations.

img
img
img

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

/*
addLast 10
addLast 20
addLast 30
addLast 40
addLast 50
quit
*/
public class Add_Last_In_LinkedList {

static class Node {
int data;
Node next;
}

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

// Write your code here
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 = tail.next;
}
size++;
}


}

public static void testList(LinkedList list) {
for (Node temp = list.head; temp != null; temp = temp.next) {
System.out.println(temp.data);
}
System.out.println(list.size);

if (list.size > 0) {
System.out.println(list.tail.data);
}
}

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);
}
str = br.readLine();
}

testList(list);
}
}

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:...