Created
January 13, 2021 22:59
-
-
Save JoeFurfaro/1f415f8a61e93bc0c7ff1a0e69655e87 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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