Created
September 14, 2018 14:40
-
-
Save panwarab/c32ecb13603e6fbee9858ecd76491b11 to your computer and use it in GitHub Desktop.
linked list implementation in java
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
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