Skip to content

Instantly share code, notes, and snippets.

@panwarab
Created September 14, 2018 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panwarab/c32ecb13603e6fbee9858ecd76491b11 to your computer and use it in GitHub Desktop.
Save panwarab/c32ecb13603e6fbee9858ecd76491b11 to your computer and use it in GitHub Desktop.
linked list implementation in java
import java.util.Scanner;
class ListNode {
private int value;
private ListNode nextNode;
public ListNode() {
value = -1;
nextNode = null;
}
public ListNode getNextNode() {
return nextNode;
}
public void setNextNode(ListNode nextNode) {
this.nextNode = nextNode;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
class LinkedList {
ListNode head;
ListNode root;
public LinkedList() {
head = new ListNode();
root = head;
}
public void add(int num) {
ListNode node = new ListNode();
node.setValue(num);
head.setNextNode(node);
head = head.getNextNode();
}
public void printAll() {
System.out.println("printing your list");
ListNode iterator = root.getNextNode();
while (iterator!=null) {
System.out.println(iterator.getValue());
iterator=iterator.getNextNode();
}
}
}
class Driver {
public static void main(String[] args) {
System.out.println("Enter -1 to exit, else continue inputting numbers into the list");
Scanner sc = new Scanner(System.in);
LinkedList myList = new LinkedList();
do {
int number = sc.nextInt();
if (number == -1) {
try {
throw new Exception("User pressed -1:: No more input accepted");
} catch (Exception e) {
System.out.println("Exception Raised " + e.getMessage());
myList.printAll();
}
} else {
myList.add(number);
System.out.println(number+" added succesfully");
}
} while (true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment