Linked List Java Lecture 24
Linked List Java Lecture 24
Java
Linked List
import java.util.*;
class LL {
public static void main(String args[]) {
LinkedList<String> list = new LinkedList<String>();
list.add("is");
list.add("a");
list.addLast("list");
list.addFirst("this");
list.add(3, "linked");
System.out.println(list);
System.out.println(list.get(0));
System.out.println(list.size());
list.remove(3);
list.removeFirst();
list.removeLast();
System.out.println(list);
}
}
Apna College
Scratch Implementation (Important for BEGINNERS)
class LL {
Node head;
LL () {
size = 0;
String data;
Node next;
Node(String data) {
this.data = data;
this.next = null;
size++;
newNode.next = head;
head = newNode;
Apna College
public void addLast(String data) {
if(head == null) {
head = newNode;
return;
while(lastNode.next != null) {
lastNode = lastNode.next;
lastNode.next = newNode;
while(currNode != null) {
currNode = currNode.next;
System.out.println("null");
Apna College
}
if(head == null) {
return;
head = this.head.next;
size--;
if(head == null) {
return;
size--;
if(head.next == null) {
head = null;
return;
Apna College
while(lastNode.next != null) {
currNode = currNode.next;
lastNode = lastNode.next;
currNode.next = null;
return size;
list.addLast("is");
list.addLast("a");
list.addLast("list");
list.printList();
list.addFirst("this");
list.printList();
System.out.println(list.getSize());
list.removeFirst();
Apna College
list.printList();
list.removeLast();
list.printList();
How to insert in the middle of a Linked List (at a specified index ‘i’) ?
Scratch
public void addInMiddle(int index, String data) {
return;
size++;
newNode.next = head;
head = newNode;
return;
if(i == index) {
Apna College
Node nextNode = currNode.next;
currNode.next = newNode;
newNode.next = nextNode;
break;
currNode = currNode.next;
LinkedList class
import java.util.*;
class LL {
list.addFirst("shradha");
list.addFirst("name");
list.addFirst("my");
System.out.println(list);
list.add(2, "is");
System.out.println(list);
Apna College
Homework Problems
1. Make a Linked List & add the following elements to it : (1, 5, 7, 3 , 8, 2, 3).
Search for the number 7 & display its index.
2. Take elements(numbers in the range of 1-50) of a Linked List as input
from the user. Delete all nodes which have values greater than 25.
Apna College