Skip to content

Instantly share code, notes, and snippets.

@JoeFurfaro
Created January 13, 2021 22:59
Show Gist options
  • Save JoeFurfaro/1f415f8a61e93bc0c7ff1a0e69655e87 to your computer and use it in GitHub Desktop.
Save JoeFurfaro/1f415f8a61e93bc0c7ff1a0e69655e87 to your computer and use it in GitHub Desktop.
public class LinkedList {
private Node head;
public LinkedList() {
head = null;
}
public void append(int n) {
if(head == null) {
head = new Node(n);
} else {
Node curNode = head;
while(curNode.getNext() != null)
curNode = curNode.getNext();
curNode.setNext(new Node(n));
}
}
public boolean delete(int n) {
if(head.getValue() == n) {
head = head.getNext();
return true;
} else {
Node lastNode = null;
Node curNode = head;
while(curNode.getValue() != n && curNode.getNext() != null) {
lastNode = curNode;
curNode = curNode.getNext();
}
if(curNode.getValue() == n) {
lastNode.setNext(curNode.getNext());
return true;
}
return false;
}
}
public void print() {
if(head == null) {
System.out.println("EMPTY");
} else {
Node curNode = head;
while(curNode.getNext() != null) {
System.out.print(curNode.getValue() + " -> ");
curNode = curNode.getNext();
}
System.out.print(curNode.getValue());
System.out.println();
}
}
}
public class Main {
public static void main(String[] args) {
LinkedList L = new LinkedList();
L.append(3);
L.append(6);
L.append(9);
L.print();
System.out.println(L.delete(5));
L.print();
}
}
public class Node {
private int value;
private Node next;
public Node(int value) {
this.value = value;
this.next = null;
}
public int getValue() {
return value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment