Skip to content

Instantly share code, notes, and snippets.

@aquibbaig
Created April 7, 2019 10:16
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 aquibbaig/2681a101f1f4bdbd22c17903681f7b72 to your computer and use it in GitHub Desktop.
Save aquibbaig/2681a101f1f4bdbd22c17903681f7b72 to your computer and use it in GitHub Desktop.
LinkedList Implementation
import java.util.*;
public class List{
Node head;
List(){
head = null;
}
static class Node{
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
public static void showList(List l){
System.out.println("===========");
Node current = l.head;
while(current != null) {
System.out.println(current.data);
current = current.next;
}
System.out.println("===========");
executeList(l);
}
public static void createElement(List l){
System.out.println("Creating an element on the top");
System.out.println("Enter the element to enter at the top");
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
System.out.println("===========");
Node new_node = new Node(number);
if(l.head == null) {
l.head = new_node;
} else {
Node temp;
temp = l.head;
l.head = new_node;
l.head.next = temp;
}
System.out.println("Inserted");
executeList(l);
}
public static void deleteElement(List ll, int element){
try
{
if(ll.head.data == element) {
ll.head = ll.head.next;
}
else {
Node current = ll.head;
while(current.next != null) {
if(current.next.data == element) {
current.next = (current.next).next;
}
current = current.next;
}
}
showList(ll);
} catch (java.lang.NullPointerException exception) {
System.out.println(exception);
}
}
public static void reverseList(List l){
Node currentNode = l.head;
Node prevNode = null;
Node nextNode = null;
while(currentNode != null){
System.out.println(currentNode);
nextNode = currentNode.next;
currentNode.next = prevNode;
prevNode = currentNode;
currentNode = nextNode;
}
l.head = prevNode;
showList(l);
}
public static void showListOperations() {
System.out.println("1 - Create an element");
System.out.println("2 - Delete element");
System.out.println("3 - Show list");
System.out.println("4 - Reverse the list");
System.out.println("===========");
}
public static void executeList(List list){
showListOperations();
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
System.out.println("Executing");
if (input == 1) {
createElement(list);
}
if(input == 2) {
// TODO: Do while loop for deletion of last element
System.out.println("Enter element to delete...");
Scanner scs = new Scanner(System.in);
int element = scs.nextInt();
deleteElement(list, element);
}
else if (input == 3) {
showList(list);
}
else if (input == 4) {
System.out.println("Reversing a linked list..");
reverseList(list);
}
}
public static void main(String args[]) {
List l = new List();
executeList(l);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment