Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions Linked List/SLL.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
class SLL {

Node head;
private int size;

SLL () {
size = 0;
}

public class Node {
String data;
Node next;

Node(String data) {
this.data = data;
this.next = null;
size++;
}
}

public void addFirst(String data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
public void addLast(String data) {
Node newNode = new Node(data);

if(head == null) {
head = newNode;
return;
}

Node lastNode = head;
while(lastNode.next != null) {
lastNode = lastNode.next;
}

lastNode.next = newNode;
}

public void printList() {
Node currNode = head;

while(currNode != null) {
System.out.print(currNode.data+" -> ");
currNode = currNode.next;
}

System.out.println("null");

}

public void removeFirst() {
if(head == null) {
System.out.println("Empty List, nothing to delete");
return;
}

head = this.head.next;
size--;
}

public void removeLast() {
if(head == null) {
System.out.println("Empty List, nothing to delete");
return;
}

size--;
if(head.next == null) {
head = null;
return;
}

Node currNode = head;
Node lastNode = head.next;

while(lastNode.next != null) {
currNode = currNode.next;
lastNode = lastNode.next;
}

currNode.next = null;
}

public int getSize() {
return size;
}



public static void main(String args[]) {
SLL list = new SLL();
list.addLast("is");
list.addLast("a");
list.addLast("list");
list.printList();

list.addFirst("this");
list.printList();
System.out.println(list.getSize());

list.removeFirst();
list.printList();

list.removeLast();
list.printList();
}
}