Searching difference between two different linked list - java

I'm having a problem with my two methods "oneTwo" and "twoOne" of which the "result" list did not give any output when I printed it.
this is the case that i've made :
add list1 ana
add list2 ana
add list1 ben
add list2 bob
add list1 james
add list2 james
print_difference list1 list2
for some reason, it didnt give me any output, but "print list1" would.
import java.util.Scanner;
class Node{
Object data;
Node next;
Node prev;
public Node() {
}
public Node(Object data) {
this(data,null,null);
}
public Node(Object data,Node next,Node prev) {
this.data=data;
this.next=next;
this.prev=prev;
}
}
class DoublyLinkedList {
Node head,tail;
int size;
public DoublyLinkedList() {
makeEmpty();
}
public boolean isEmpty() {
return size == 0;
}
public void makeEmpty() {
head=tail=null;
size=0;
}
public int size() {
return size;
}
//adding
public void addLast(Object x) {
Node tmp=new Node(x);
if (head==null && tail==null) {
head=tail=tmp;
size++;
}else {
tmp.prev=tail;
tail.next=tmp;
tmp.next=null;
tail=tmp;
size++;
}
}
//print
public void print() {
Node p=head;
while(p!=null) {
System.out.print(p.data);
if(p.next!=null) {
System.out.print("-");
}
p=p.next;
}
System.out.println();
}
this is the part that seems to be not working on me
//compare
void oneTwo(DoublyLinkedList a) {
DoublyLinkedList result=new DoublyLinkedList();
Node p=head;
do {
boolean check=a.searchByData(p.data);
if(check==false) {
result.addLast(p.data);
}
p=p.next;
}while(p.next!=null);
System.out.print("LIST_difference1 : ");
result.print();
}
void twoOne(DoublyLinkedList a) {
DoublyLinkedList result=new DoublyLinkedList();
Node p=head;
do {
boolean check=a.searchByData(p.data);
if(check==false) {
result.addLast(p.data);
}
p=p.next;
}while(p.next!=null);
System.out.print("LIST_difference2 : ");
result.print();
}
there aren't any output prom the "result.print();"
public boolean searchByData(Object x) {
Node search=head;
boolean check=false;
while(search.data != x) {
if(search.data.equals(x)) {
check=true;
break;
}
if(search.next!=null) {
search=search.next;
}else {
check=false;
}
}
return check;
}
}
public class FindTheDifference {
public static void main(String[] args) {
DoublyLinkedList one=new DoublyLinkedList();
DoublyLinkedList two=new DoublyLinkedList();
while (true){
Scanner scan=new Scanner(System.in);
String input=scan.nextLine();
String[] inputs=input.trim().split(" ");
if(inputs[0].equalsIgnoreCase("add")) {
if(inputs[1].equalsIgnoreCase("list1")) {
one.addLast(inputs[2]);
}else {
two.addLast(inputs[2]);
}
}else if(inputs[0].equalsIgnoreCase("print")) {
if(inputs[1].equalsIgnoreCase("list1")) {
one.print();
}else {
two.print();
}
}else if(inputs[0].equalsIgnoreCase("print_difference")) {
if(inputs[1].equalsIgnoreCase("list1") && inputs[2].equalsIgnoreCase("list2")) {
one.oneTwo(two);
}else if(inputs[1].equalsIgnoreCase("list2") && inputs[2].equalsIgnoreCase("list1")) {
two.twoOne(one);
}
}
}
}
}
what is wrong with my code? any help would be appreciated.

Because a dead loop has occurred in a.searchByData()
like this
public boolean searchByData(Object x) {
Node search = head;
boolean check = false;
while (search.data != x) {
if (search.data.equals(x)) {
check = true;
break;
}
if (search.next != null) {
search = search.next;
} else {
//If it doesn't match here and it's at the end of the linked list
//should break
check = false;
break;
}
}
return check;
}

Related

Inserting an integer into a regular binary tree

While revising for my final, I came across binary trees (regular ones). After going through the lecture, I started to solve previous labs.
My problem here is that only 6 is inserted into the tree. What is wrong with my method?
What I'm trying to input:
tree.insert(1); tree.insert(15); tree.insert(7);
tree.insert(13); tree.insert(58); tree.insert(6);
The Node class:
public class Node {
public int key;
public Node left_child;
public Node right_child;
// The Constructor(s).
public Node() {
}
public Node(int key) {
this.key = key;
left_child = null;
right_child = null;
}
// The Get Methods.
public int getKey() {
return key;
}
public Node getLeft_child() {
return left_child;
}
public Node getRight_child() {
return right_child;
}
// The Set Methods.
public void setKey(int key) {
this.key = key;
}
public void setLeft_child(Node left_child) {
this.left_child = left_child;
}
public void setRight_child(Node right_child) {
this.right_child = right_child;
}
}
The BinaryTree class:
public class BinaryTree {
private Node root;
// The Constructor Method(s)
public BinaryTree() {
root = null;
}
public boolean is_empty() {
return (root == null);
}
public void insert(int k) {
insert(root, k);
}
private Node insert(Node x, int k) {
Node p = new Node(k);
if (x == null) {
root = p;
}
else {
if (x.left_child != null) {
insert(x.left_child, k);
}
else {
insert(x.right_child, k);
}
}
return x;
}
// Printing Method(s).
public void print_inorder() {
print_inorder(root);
}
public void print_inorder(Node node) {
if (node == null) {
return;
}
print_inorder(node.left_child);
System.out.print(node.key + " ");
print_inorder(node.right_child);
}
public void print_preorder() {
print_preorder(root);
}
public void print_preorder(Node node) {
if (node == null) {
return;
}
System.out.print(node.key + " ");
print_preorder(node.left_child);
print_preorder(node.right_child);
}
public void print_postorder() {
print_postorder(root);
}
public void print_postorder(Node node) {
if (node == null) {
return;
}
print_postorder(node.left_child);
print_postorder(node.right_child);
System.out.print(node.key + " ");
}
}
This will have a node to the left if a number is even and a node to the right if a node is odd.
I had to change your if condition because the way it was it was never going to use the left node.
private void insert(Node x, int k) {
Node p = new Node(k);
if (root == null) {
this.root = p;
return;
}
if (x.getKey() - k % 2 == 0) {
if (x.left_child == null) {
x.left_child = p;
} else {
insert(x.left_child, k);
}
} else {
if (x.right_child == null) {
x.right_child = p;
} else {
insert(x.right_child, k);
}
}
}

Time out issue in java

I have been running this code and it seems like it times out. I'm not sure how to fix it as it doesn't show me an actual error message or anything like that. The first block of code is the class that the methods in the demo are coming from, and it seems like all the methods that are being called for stringList are just not working. When I test the same thing with an int list it works fine.
public class DoublyLinkedList<E> {
private static class Node<E> {
// Node Fields
private E element; //data
private Node<E> prev; //previous Node
private Node<E> next; //next Node
// Node Constructor
public Node(E e, Node<E> p, Node<E> n) {
this.element = e;
this.prev = p;
this.next = n;
}
// Node Methods
public E getElement() {
return element;
}
public Node<E> getPrev() {
return this.prev;
}
public Node<E> getNext() {
return this.next;
}
public void setPrev(Node<E> p) {
this.prev = p;
}
public void setNext(Node<E> n) {
this.next = n;
}
}
// DLinkedList Fields
private Node<E> header;
private Node<E> trailer;
int size;
// DLinkedList Constructor
public DoublyLinkedList() {
this.header = new Node<>(null, null, null);
this.trailer = new Node<>(null, this.header, null);
this.header.setNext(this.trailer);
}
// DLinkedList Methods
public int size() {
return this.size;
}
public E first() {
if (isEmpty()) {
return null;
}
return this.header.next.getElement();
}
public E last () {
if (isEmpty()) {
return null;
}
return this.trailer.prev.getElement();
}
public boolean isEmpty() {
return size == 0;
}
public void addFirst (E e) {
addBetween(e, this.header, this.header.getNext());
}
public void addLast (E e) {
addBetween(e, this.trailer.getPrev(), this.trailer);
}
private void addBetween(E e, Node<E> predecessor, Node<E> successor) {
Node<E> newest = new Node<>(e, predecessor, successor);
predecessor.setNext(newest);
successor.setPrev(newest);
this.size++;
}
public E removeFirst() {
if (this.isEmpty()) {
return null;
}
return this.remove(header.getNext());
}
public E removeLast() {
if (this.isEmpty()) {
return null;
}
return this.remove(trailer.getPrev());
}
public E remove(Node<E> e) {
e.next.setPrev(e.prev);
e.prev.setNext(e.next);
this.size--;
return e.getElement();
}
public String toString() {
StringBuilder sb = new StringBuilder("(");
Node<E> walk = this.header.next;
while (walk != this.trailer) {
sb.append(walk.element);
if (walk.next != this.trailer)
sb.append(", ");
walk = walk.next;
}
sb.append(")");
return sb.toString();
}
//DONE
public void add(int index, E element) {
Node<E> pred = header;
Node<E> succ = pred.getNext();
int count = 0;
while(succ != null) {
if(count == index) addBetween(element, pred, succ);
count++;
pred = pred.getNext();
succ = succ.getNext();
}
}
//DONE
public void add(E e) {
add(size, e);
}
//DONE
public void clear() {
while(!isEmpty()) {
removeFirst();
}
}
public E get(int index) {
if (isEmpty()) return null;
Node<E> current = header;
int count = 0;
while(current != null) {
if(count == index) return current.getElement();
count++;
current = current.getNext();
}
return null;
}
public E set(int index, E element) {
if(isEmpty()) return null;
Node<E> current = header;
E returnVal = null;
int count = 0;
while(current != null) {
if(count == index) {
if(count == 0) {
returnVal = get(0);
removeFirst();
add(0, element);
}
else if(count == size) {
returnVal = get(size);
removeLast();
add(size, element);
}
else {
returnVal = get(index);
remove(current);
add(index, element);
}
}
}
return returnVal;
}
}
package labs;
public class DoublyLinkedListDemo {
public static void main(String[] args) {
//testing methods on a String DoublyList
DoublyLinkedList<String> stringList = new DoublyLinkedList<>();
stringList.addFirst("Strawberry");
stringList.addFirst("Banana");
stringList.addFirst("Apple");
stringList.set(0, stringList.get(1));
System.out.println(stringList);
stringList.add(1, "Pear");
System.out.println(stringList);
stringList.add("Blueberry");
System.out.println(stringList);
System.out.println(stringList.get(1));
stringList.clear();
System.out.println(stringList);
System.out.println(stringList.set(0, stringList.get(1)));
System.out.println(stringList.get(0));
}
}

BST Node Deletion Confusion [JaVa]

I've created a Binary Search Tree in JaVa. Unfortunately 'delete' function doesn't work. I will be really appreciated if you could take a look. Thanks in advance..
Problem: I can't inorder print the tree after I delete a node from it.
Node:
class Node {
//Properties
private Node left, right, parent;
private int key;
//Getters and Setters
public Node(int key) {
this.key = key;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
}
Binary Search Tree:
public class BinarySearchTree {
//Properties
private Node root;
//Getters and Setters
Node getRoot() {
return root;
}
public void setRoot(Node root) {
this.root = root;
}
//Search Method
public Node search(Node x, int k){
if (x == null || k==x.getKey()){
return x;
}
if (k<x.getKey()){
return search(x.getLeft(), k);
}
else{
return search(x.getRight(), k);
}
}
//Insertion Method
public void insert(Node z) {
Node y = null;
Node x = getRoot();
while (x != null) {
y = x;
if (z.getKey() < x.getKey()) {
x = x.getLeft();
} else {
x = x.getRight();
}
}
z.setParent(y);
if (y == null) {
setRoot(z);
} else if (z.getKey() < y.getKey()) {
y.setLeft(z);
} else {
y.setRight(z);
}
}
//Printer Method
public void inorder(Node x) {
if (x != null) {
inorder(x.getLeft());
System.out.print(x.getKey() + " ");
inorder(x.getRight());
}
}
//Transplant Method
public void transplant(Node u, Node v){
if (u.getParent() == null){
setRoot(v);
}
else if (u==u.getParent().getLeft()){
u.getParent().setLeft(v);
}
else{
u.getParent().setRight(v);
}
if (v!=null){
v.setParent(u.getParent());
}
}
//Deletion Method
public void delete(Node x) {
if (x.getLeft() == null) {
transplant(x, x.getRight());
} else if (x.getRight() == null) {
transplant(x, x.getLeft());
} else {
Node y = minimum(x.getRight());
if (y.getParent() != x) {
transplant(y, y.getRight());
y.setRight(x.getRight());
y.getRight().setParent(y);
}
transplant(x, y);
y.setLeft(x.getLeft());
y.getLeft().setParent(y);
}
}
//Maximum Finder
public Node maximum(Node x) {
while (x.getRight() != null) {
x = x.getRight();
}
return x;
}
//Minimum Finder
public Node minimum(Node x) {
while (x.getLeft() != null) {
x = x.getLeft();
}
return x;
}
//Example Tree Constructor
public void createBST(int[] a){
for (int i=0; i<a.length; i++){
Node nodeToBeAdded = new Node(a[i]);
insert(nodeToBeAdded);
}
inorder(root);
}
}
and a Test class:
public class Test {
public static void main(String[] args) {
//CREATION
System.out.println("CREATION");
BinarySearchTree tree = new BinarySearchTree();
int[] a = {54, 32, 76, 7, 44, 63, 99};
tree.createBST(a);
System.out.println();
System.out.print("The root of the tree is: ");
System.out.println();
System.out.print("Maximum Node is: ");
tree.inorder(tree.maximum(tree.getRoot()));
System.out.println();
System.out.print("Minimum Node is: ");
tree.inorder(tree.minimum(tree.getRoot()));
System.out.println();
//INSERTION
System.out.println("INSERTION");
tree.insert(new Node(25));
tree.inorder(tree.getRoot());
tree.insert(new Node(485));
System.out.println();
tree.inorder(tree.getRoot());
tree.insert(new Node(12));
System.out.println();
tree.inorder(tree.getRoot());
tree.insert(new Node(5));
System.out.println();
tree.inorder(tree.getRoot());
tree.insert(new Node(9985));
System.out.println();
tree.inorder(tree.getRoot());
System.out.println();
System.out.print("Maximum Node is: ");
tree.inorder(tree.maximum(tree.getRoot()));
System.out.println();
System.out.print("Minimum Node is: ");
tree.inorder(tree.minimum(tree.getRoot()));
System.out.println();
//SEARCH
System.out.println("SEARCH");
tree.inorder(tree.search(tree.getRoot(), 32));
System.out.println();
//DELETION
System.out.println("DELETION");
tree.delete(new Node(5));
tree.inorder(tree.getRoot());
}
}
As i can see you don't override equals/hashCode methods so you can't find Node(5) because you created new instance. If you change your code in Test.java:
tree.insert(new Node(12));
System.out.println();
tree.inorder(tree.getRoot());
// Start changes
Node node5 = new Node(5);
tree.insert(node5);
System.out.println();
tree.inorder(tree.getRoot());
// End changes
tree.insert(new Node(9985));
// -cut some code
//DELETION
System.out.println("DELETION");
tree.delete(node5);
System.out.println();
tree.inorder(tree.getRoot());
it will print result

Why will my program not go into my while loop?

I'm working on a program that will take a name and number of a periodic element, store it in a tree and then print it out in different orders.
When I try and run my main class it asks for the name, but then it doesn't go into the while loop.
Here is my main class.
public class BinarySearchTree
{
public static void main(String[] args)
{
Scanner conIn = new Scanner(System.in);
String name;
int atomicNum;
BSTInterface<PeriodicElement> elements = new BSTree<PeriodicElement>();
PeriodicElement element;
int numElements;
String skip;
System.out.print("Element name (press Enter to end): ");
name = conIn.nextLine();
while (!name.equals(""));
{
System.out.print("Atomic Number: ");
atomicNum = conIn.nextInt();
skip = conIn.nextLine();
element = new PeriodicElement(name, atomicNum);
elements.add(element);
System.out.print("Element name (press ENTER TO END): ");
name = conIn.nextLine();
}
System.out.println();
System.out.println("Periodic Elements");
numElements = elements.reset(BSTree.INORDER);
for (int count = 1; count <= numElements; count++)
{
System.out.println(elements.getNext(BSTree.INORDER));
}
}
}
Here is my Binary Search Tree
public class BSTree <T extends Comparable<T>>
implements BSTInterface<T>
{
protected BSTNode<T> root;
boolean found;
protected LinkedUnbndQueue<T> inOrderQueue;
protected LinkedUnbndQueue<T> preOrderQueue;
protected LinkedUnbndQueue<T> postOrderQueue;
public BSTree()
{
root = null;
}
public boolean isEmpty()
{
return (root == null);
}
private int recSize(BSTNode<T> tree)
{
if(tree == null)
{
return 0;
}
else
{
return recSize(tree.getLeft()) + recSize(tree.getRight()) + 1;
}
}
public int size()
{
int count = 0;
{
if(root != null)
{
LinkedStack<BSTNode<T>> hold = new LinkedStack<BSTNode<T>>();
BSTNode<T> currNode;
hold.push(root);
while(!hold.isEmpty())
{
currNode = hold.top();
hold.pop();
count++;
if(currNode.getLeft() != null)
{
hold.push(currNode.getLeft());
}
if(currNode.getRight() != null)
{
hold.push(currNode.getRight());
}
}
}
//System.out.println(count);
return count;
}
}
public boolean recContains(T element, BSTNode<T> tree)
{
if(tree == null)
{
return false;
}
else if(element.compareTo(tree.getInfo()) < 0)
{
return recContains(element, tree.getLeft());
}
else if(element.compareTo(tree.getInfo()) > 0)
{
return recContains(element, tree.getRight());
}
else
{
return true;
}
}
public boolean contains (T element)
{
//System.out.println("Tree contains: " + recContains(element, root));
return recContains(element, root);
}
public T recGet(T element, BSTNode<T> tree)
{
if(tree == null)
{
return null;
}
else if(element.compareTo(tree.getInfo()) < 0)
{
return recGet(element, tree.getLeft());
}
else if(element.compareTo(tree.getInfo()) > 0)
{
return recGet(element, tree.getRight());
}
else
{
return tree.getInfo();
}
}
public T get(T element)
{
//System.out.println(recGet(element, root));
return recGet(element, root);
}
public void add(T element)
{
root = recAdd(element, root);
}
private BSTNode<T> recAdd(T element, BSTNode<T> tree)
{
if(tree == null)
{
tree = new BSTNode<T>(element);
}
else if(element.compareTo(tree.getInfo()) <= 0)
{
tree.setLeft(recAdd(element, tree.getLeft()));
}
else
{
tree.setRight(recAdd(element, tree.getRight()));
}
return tree;
}
public boolean remove(T element)
{
root = recRemove(element, root);
return found;
}
private BSTNode<T> recRemove(T element, BSTNode<T> tree)
{
if(tree == null)
{
found = false;
}
else if (element.compareTo(tree.getInfo()) < 0)
{
tree.setLeft(recRemove(element, tree.getLeft()));
}
else if (element.compareTo(tree.getInfo()) > 0)
{
tree.setRight(recRemove(element, tree.getRight()));
}
else
{
tree = removeNode(tree);
found = true;
}
return tree;
}
private BSTNode<T> removeNode(BSTNode<T> tree)
{
T data;
if(tree.getLeft() == null)
{
return tree.getRight();
}
else if(tree.getRight() == null)
{
return tree.getLeft();
}
else
{
data = getPredecessor(tree.getLeft());
tree.setInfo(data);
tree.setLeft(recRemove(data, tree.getLeft()));
return tree;
}
}
private T getPredecessor(BSTNode<T> tree)
{
while (tree.getRight() != null)
{
tree = tree.getRight();
}
return tree.getInfo();
}
public int reset(int orderType)
{
int numNodes = size();
if(orderType == INORDER)
{
inOrderQueue = new LinkedUnbndQueue<T>(numNodes);
}
else
{
if(orderType == PREORDER)
{
preOrderQueue = new LinkedUnbndQueue<T>(numNodes);
preOrder(root);
}
if(orderType == POSTORDER)
{
postOrderQueue = new LinkedUnbndQueue<T>(numNodes);
postOrder(root);
}
}
return numNodes;
}
public T getNext(int orderType)
{
if(orderType == INORDER)
{
return inOrderQueue.dequeue();
}
else
{
if(orderType == PREORDER)
{
return preOrderQueue.dequeue();
}
else
{
if(orderType == POSTORDER)
{
return postOrderQueue.dequeue();
}
else
{
return null;
}
}
}
}
private void inOrder(BSTNode<T> tree)
{
if(tree != null)
{
inOrder(tree.getLeft());
inOrderQueue.enqueue(tree.getInfo());
inOrder(tree.getRight());
}
}
private void preOrder(BSTNode<T> tree)
{
if(tree != null)
{
preOrderQueue.enqueue(tree.getInfo());
preOrder(tree.getLeft());
preOrder(tree.getRight());
}
}
private void postOrder(BSTNode<T> tree)
{
if(tree != null)
{
postOrder(tree.getLeft());
postOrder(tree.getRight());
postOrderQueue.enqueue(tree.getInfo());
}
}
}
Here is the Binary Search Tree Node class
public class BSTNode <T extends Comparable<T>>
{
protected T info;
protected BSTNode<T> left;
protected BSTNode<T> right;
public BSTNode(T info)
{
this.info = info;
left = null;
right = null;
}
public void setInfo(T info)
{
this.info = info;
}
public T getInfo()
{
return info;
}
public void setLeft(BSTNode<T> link)
{
left = link;
}
public void setRight(BSTNode<T> link)
{
right = link;
}
public BSTNode<T> getLeft()
{
return left;
}
public BSTNode<T> getRight()
{
return right;
}
}
Remove the semi-colon that is terminating the while statement
while (!name.equals(""));
^
Remove the semi colon after the while statment because a semi colon makes it end there while a { is the start if while something is true or not (!) and it should end as you obviously know with a }.

linked list implementation java

I have implemented a Linked List into Java. I have created everything, but I am having difficulty removing a specific node with specific data. It is throwing a NullPointerException. I believe, I am getting a NullPointerException because the next node is null. If someone could please point me in the right direction that would be great.
Input
anything
one
two
three
exception:
Exception in thread "main" java.lang.NullPointerException
at LinkedList.remove(LinkedList.java:28)
at Main.main(Main.java:29)
Classes:
Linked list class
public class LinkedList {
// fields
private Node head;
private Node last;
private int size = 0;
// constructor, used when the class is first called
public LinkedList() {
head = last = new Node(null);
}
// add method
public void add(String s) {
last.setNext(new Node(s));
last = last.getNext();
size++;
}
// remove method, if it returns false then the specified index element doens not exist
// otherwise will return true
public boolean remove(String data) {
Node current = head;
last = null;
while(current != null) {
if(current.getData().equals(data)) {
current = current.getNext();
if(last == null) {
last = current;
}else {
last.getNext().setNext(current);
size--;
return true;
}
}else {
last = current;
current = current.getNext();
}
}
return false;
}
//will return the size of the list - will return -1 if list is empty
public int size() {
return size;
}
// will check if the list is empty or not
public boolean isEmpty() {
return true;
}
// #param (index) will get the data at specified index
public String getData(int index) {
if(index <= 0) {
return null;
}
Node current = head.getNext();
for(int i = 1;i < index;i++) {
if(current.getNext() == null) {
return null;
}
current = current.getNext();
}
return current.getData();
}
//#param will check if the arguement passed is in the list
// will return true if the list contains arg otherwise false
public boolean contains(String s) {
for(int i = 1;i<=size();i++) {
if(getData(i).equals(s)) {
return true;
}
}
return false;
}
//#return contents of the list - recursively
public String toString() {
Node current = head.getNext();
String output = "[";
while(current != null) {
output += current.getData()+",";
current = current.getNext();
}
return output+"]";
}
//#return first node
public Node getHead() {
return head;
}
// #return (recursively) list
public void print(Node n) {
if(n == null) {
return;
}else {
System.out.println(n.getData());
print(n.getNext());
}
}
}
Main
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException{
LinkedList list = new LinkedList(); // declaring main linked list
LinkedList b_List = new LinkedList(); // declaring the backup list
String input = null;
// getting input from user, will stop when user has entered 'fin'
while(!(input = br.readLine()).equals("fin")) {
list.add(input); // adding to main list
b_List.add(input);
}
list.print(list.getHead().getNext());
System.out.println("Input Complete.");
if(list.size() == 1) {
System.out.println("You have entered only one name. He/She is the survior");
}else {
System.out.println("Enter the name(s) would like to remove: ");
while(b_List.size() != 1) {
String toRemove = br.readLine();
b_List.remove(toRemove);
}
}
System.out.println("The contestants were: ");
list.print(list.getHead().getNext());
}
}
node
public class Node {
// Fields
private String data;
private Node next;
// constructor
public Node(String data) {
this(data,null);
}
// constructor two with Node parameter
public Node(String data, Node node) {
this.data = data;
next = node;
}
/**
* Methods below return information about fields within class
* */
// #return the data
public String getData() {
return data;
}
// #param String data to this.data
public void setData(String data) {
this.data = data;
}
// #return next
public Node getNext() {
return next;
}
// #param Node next set to this.next
public void setNext(Node next) {
this.next = next;
}
}
First of all, your head is just a before-first marker so you shouldn't start the remove check from it.
Second, your remove method fails if node data is null
Third - your implementation is broken anyway because of last.getNext().setNext(current) - it won't link previous node with next, it will link current to next (i.e. will do nothing)
Fourth - it still fails to remove first element because of mysterious operations with last...
Correct implementation of remove would be something like this:
public boolean remove(String data){
Node previous = head;
Node current = head.getNext();
while (current != null) {
String dataOld = current.getData();
if ((dataOld == null && data == null) || (dataOld != null && dataOld.equals(data))) {
Node afterRemoved = current.getNext();
previous.setNext(afterRemoved);
if (afterRemoved == null) { // i.e. removing last element
last = previous;
}
size--;
return true;
} else {
previous = current;
current = current.getNext();
}
}
return false;
}
Here we can see the simple implementation of LinkedList with iterator
class LinkedList implements Iterable{
private Node node;
public void add(Object data){
if(!Optional.ofNullable(node).isPresent()){
node = new Node();
node.setData(data);
}else{
Node node = new Node();
node.setData(data);
Node lastNode = getLastNode(this.node);
lastNode.setNext(node);
}
}
private Node getLastNode(Node node){
if(node.getNext()==null){
return node;
}else{
return getLastNode(node.getNext());
}
}
class Node{
private Object data;
private Node next;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public Iterator iterator() {
return new NodeIterator();
}
class NodeIterator implements Iterator{
private Node current;
public boolean hasNext() {
if(current == null){
current = node;
return Optional.ofNullable(current).isPresent();
}else{
current = current.next;
return Optional.ofNullable(current).isPresent();
}
}
public Node next() {
return current;
}
}
}
public class LinkedListImpl {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.add("data1");
linkedList.add("data2");
linkedList.add("data3");
for(LinkedList.Node node: linkedList){
System.out.println(node.getData());
}
}
}
Here is Full Implementaion of Linked List
including insertion,deletion,searching,reversing,swaping,size,display and various important operations of linked list
import java.util.NoSuchElementException;
import java.util.Scanner;
class Node<T> {
public Node<T> next;
public T data;
public Node() {
}
public Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
#Override
public String toString() {
return "Node [next=" + next + ", data=" + data + "]";
}
}
class LinkedList<T> {
Node<T> start = null;
Node<T> end = null;
public void insertAtStart(T data) {
Node<T> nptr = new Node<T>(data, null);
if (empty()) {
start = nptr;
end = start;
} else {
nptr.next = start;
start = nptr;
}
display();
}
public void insertAtEnd(T data) {
Node<T> nptr = new Node<T>(data, null);
if (empty()) {
insertAtStart(data);
return;
} else {
end.next = nptr;
end = nptr;
}
display();
}
public void insertAtPosition(int position, T data) {
if (position != 1 && empty())
throw new IllegalArgumentException("Empty");
if (position == 1) {
insertAtStart(data);
return;
}
Node<T> nptr = new Node<T>(data, null);
if (position == size()) {
Node<T> startPtr = start;
Node<T> endPtr = startPtr;
while (startPtr.next != null) {
endPtr = startPtr;
startPtr = startPtr.next;
}
endPtr.next = nptr;
nptr.next = end;
} else {
position -= 1;
Node<T> startPtr = start;
for (int i = 1; i < size(); i++) {
if (i == position) {
Node<T> temp = startPtr.next;
startPtr.next = nptr;
nptr.next = temp;
}
startPtr = startPtr.next;
}
}
display();
}
public void delete(int position) {
if (empty())
throw new IllegalArgumentException("Empty");
if (position == 1) {
start = start.next;
} else if (position == size()) {
Node<T> startPtr = start;
Node<T> endPtr = start;
while (startPtr.next != null) {
endPtr = startPtr;
startPtr = startPtr.next;
}
endPtr.next = null;
end = endPtr;
} else {
position -= 1;
Node<T> startPtr = start;
for (int i = 1; i <= position; i++) {
if (i == position) {
Node<T> temp = startPtr.next.next;
startPtr.next = temp;
}
startPtr = startPtr.next;
}
}
display();
}
public int index(T data) {
if (empty())
throw new IllegalArgumentException("Empty");
return index(start, data, 0);
}
private int index(Node<T> link, T data, int index) {
if (link != null) {
if (link.data == data) {
return index;
}
return index(link.next, data, ++index);
}
return -1;
}
public void replace(int position, T data) {
if (empty())
throw new IllegalArgumentException("Empty");
if (position == 1)
start.data = data;
else if (position == size())
end.data = data;
else {
Node<T> startPtr = start;
for (int i = 1; i <= position; i++) {
if (i == position)
startPtr.data = data;
startPtr = startPtr.next;
}
}
display();
}
public void replaceRecursively(int position, T data) {
replaceRecursively(start, position, data, 1);
display();
}
private void replaceRecursively(Node<T> link, int position, T data, int count) {
if (link != null) {
if (count == position) {
link.data = data;
return;
}
replaceRecursively(link.next, position, data, ++count);
}
}
public T middle() {
if (empty())
throw new NoSuchElementException("Empty");
Node<T> slowPtr = start;
Node<T> fastPtr = start;
while (fastPtr != null && fastPtr.next != null) {
slowPtr = slowPtr.next;
fastPtr = fastPtr.next.next;
}
return slowPtr.data;
}
public int occurence(T data) {
if (empty())
throw new NoSuchElementException("Empty");
return occurence(start, data, 0);
}
private int occurence(Node<T> link, T data, int occurence) {
if (link != null) {
if (link.data == data)
++occurence;
return occurence(link.next, data, occurence);
}
return occurence;
}
public void reverseRecusively() {
reverseRecusively(start);
swapLink();
display();
}
private Node<T> reverseRecusively(Node<T> link) {
if (link == null || link.next == null)
return link;
Node<T> nextLink = link.next;
link.next = null;
Node<T> revrseList = reverseRecusively(nextLink);
nextLink.next = link;
return revrseList;
}
public void reverse() {
if (empty())
throw new NoSuchElementException("Empty");
Node<T> prevLink = null;
Node<T> currentLink = start;
Node<T> nextLink = null;
while (currentLink != null) {
nextLink = currentLink.next;
currentLink.next = prevLink;
prevLink = currentLink;
currentLink = nextLink;
}
swapLink();
display();
}
private void swapLink() {
Node<T> temp = start;
start = end;
end = temp;
}
public void swapNode(T dataOne, T dataTwo) {
if (dataOne == dataTwo)
throw new IllegalArgumentException("Can't swap " + dataOne + " and " + dataTwo + " both are same");
boolean foundDataOne = false;
boolean foundDataTwo = false;
Node<T> dataOnePtr = start;
Node<T> dataOnePrevPtr = start;
while (dataOnePtr.next != null && dataOnePtr.data != dataOne) {
dataOnePrevPtr = dataOnePtr;
dataOnePtr = dataOnePtr.next;
}
Node<T> dataTwoPtr = start;
Node<T> dataTwoPrevPtr = start;
while (dataTwoPtr.next != null && dataTwoPtr.data != dataTwo) {
dataTwoPrevPtr = dataTwoPtr;
dataTwoPtr = dataTwoPtr.next;
}
if (dataOnePtr != null && dataOnePtr.data == dataOne)
foundDataOne = true;
if (dataTwoPtr != null && dataTwoPtr.data == dataTwo)
foundDataTwo = true;
if (foundDataOne && foundDataTwo) {
if (dataOnePtr == start)
start = dataTwoPtr;
else if (dataTwoPtr == start)
start = dataOnePtr;
if (dataTwoPtr == end)
end = dataOnePtr;
else if (dataOnePtr == end)
end = dataTwoPtr;
Node<T> tempDataOnePtr = dataOnePtr.next;
Node<T> tempDataTwoPtr = dataTwoPtr.next;
dataOnePrevPtr.next = dataTwoPtr;
dataTwoPtr.next = tempDataOnePtr;
dataTwoPrevPtr.next = dataOnePtr;
dataOnePtr.next = tempDataTwoPtr;
if (dataOnePtr == dataTwoPrevPtr) {
dataTwoPtr.next = dataOnePtr;
dataOnePtr.next = tempDataTwoPtr;
} else if (dataTwoPtr == dataOnePrevPtr) {
dataOnePtr.next = dataTwoPtr;
dataTwoPtr.next = tempDataOnePtr;
}
} else
throw new NoSuchElementException("Either " + dataOne + " or " + dataTwo + " not in the list");
display();
}
public int size() {
return size(start, 0);
}
private int size(Node<T> link, int i) {
if (link == null)
return 0;
else {
int count = 1;
count += size(link.next, 0);
return count;
}
}
public void printNthNodeFromLast(int n) {
if (empty())
throw new NoSuchElementException("Empty");
Node<T> main_ptr = start;
Node<T> ref_ptr = start;
int count = 0;
while (count < n) {
if (ref_ptr == null) {
System.out.println(n + " is greater than the no of nodes in the list");
return;
}
ref_ptr = ref_ptr.next;
count++;
}
while (ref_ptr != null) {
main_ptr = main_ptr.next;
ref_ptr = ref_ptr.next;
}
System.out.println("Node no " + n + " from the last is " + main_ptr.data);
}
public void display() {
if (empty())
throw new NoSuchElementException("Empty");
display(start);
}
private void display(Node<T> link) {
if (link != null) {
System.out.print(link.data + " ");
display(link.next);
}
}
public boolean empty() {
return start == null;
}
}
public class LinkedListTest {
public static void main(String[] args) {
LinkedList<Integer> linkedList = new LinkedList<Integer>();
boolean yes = true;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("\n1. Insert At Start");
System.out.println("2. Insert At End");
System.out.println("3. Insert at Position");
System.out.println("4. Delete");
System.out.println("5. Display");
System.out.println("6. Empty status");
System.out.println("7. Get Size");
System.out.println("8. Get Index of the Item");
System.out.println("9. Replace data at given position");
System.out.println("10. Replace data at given position recusively");
System.out.println("11. Get Middle Element");
System.out.println("12. Get Occurence");
System.out.println("13. Reverse Recusively");
System.out.println("14. Reverse");
System.out.println("15. Swap the nodes");
System.out.println("16. Nth Node from last");
System.out.println("\nEnter your choice");
int choice = scanner.nextInt();
switch (choice) {
case 1:
try {
System.out.println("Enter the item");
linkedList.insertAtStart(scanner.nextInt());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 2:
try {
System.out.println("Enter the item");
linkedList.insertAtEnd(scanner.nextInt());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 3:
try {
System.out.println("Enter the position");
int position = scanner.nextInt();
if (position < 1 || position > linkedList.size()) {
System.out.println("Invalid Position");
break;
}
System.out.println("Enter the Item");
linkedList.insertAtPosition(position, scanner.nextInt());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 4:
try {
System.out.println("Enter the position");
int position = scanner.nextInt();
if (position < 1 || position > linkedList.size()) {
System.out.println("Invalid Position");
break;
}
linkedList.delete(position);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 5:
try {
linkedList.display();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 6:
System.out.println(linkedList.empty());
break;
case 7:
try {
System.out.println(linkedList.size());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 8:
try {
System.out.println(linkedList.index(scanner.nextInt()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 9:
try {
System.out.println("Enter the position");
int position = scanner.nextInt();
if (position < 1 || position > linkedList.size()) {
System.out.println("Invalid Position");
break;
}
linkedList.replace(position, scanner.nextInt());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 10:
try {
System.out.println("Enter the position");
int position = scanner.nextInt();
if (position < 1 || position > linkedList.size()) {
System.out.println("Invalid Position");
break;
}
System.out.println("Enter the item");
linkedList.replaceRecursively(position, scanner.nextInt());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 11:
try {
System.out.println(linkedList.middle());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 12:
try {
System.out.println("Enter the item");
System.out.println(linkedList.occurence(scanner.nextInt()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 13:
try {
linkedList.reverseRecusively();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 14:
try {
linkedList.reverse();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 15:
try {
System.out.println("Enter the nodes");
linkedList.swapNode(scanner.nextInt(), scanner.nextInt());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 16:
try {
System.out.println("Enter which node do you want from last");
linkedList.printNthNodeFromLast(scanner.nextInt());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
default:
System.out.println("Invalid Choice");
break;
}
} while (yes);
scanner.close();
}
}
Consider another possible implementation of a working non-recursive Linked List with generic T placeholder. It works out of the box and the code is a more simple one:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedList<T> implements Iterable<T> {
private Node first;
private Node last;
private int N;
public LinkedList() {
first = null;
last = null;
N = 0;
}
public void add(T item) {
if (item == null) { throw new NullPointerException("Null object!"); }
if (!isEmpty()) {
Node prev = last;
last = new Node(item, null);
prev.next = last;
}
else {
last = new Node(item, null);
first = last;
}
N++;
}
public boolean remove(T item) {
if (isEmpty()) { throw new IllegalStateException("Empty list!"); }
boolean result = false;
Node prev = first;
Node curr = first;
while (curr.next != null || curr == last) {
if (curr.data.equals(item)) {
// remove the last remaining element
if (N == 1) { first = null; last = null; }
// remove first element
else if (curr.equals(first)) { first = first.next; }
// remove last element
else if (curr.equals(last)) { last = prev; last.next = null; }
// remove element
else { prev.next = curr.next; }
N--;
result = true;
break;
}
prev = curr;
curr = prev.next;
}
return result;
}
public int size() {
return N;
}
public boolean isEmpty() {
return N == 0;
}
private class Node {
private T data;
private Node next;
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
}
public Iterator<T> iterator() { return new LinkedListIterator(); }
private class LinkedListIterator implements Iterator<T> {
private Node current = first;
public T next() {
if (!hasNext()) { throw new NoSuchElementException(); }
T item = current.data;
current = current.next;
return item;
}
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }
}
#Override public String toString() {
StringBuilder s = new StringBuilder();
for (T item : this)
s.append(item + " ");
return s.toString();
}
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
while(!StdIn.isEmpty()) {
String input = StdIn.readString();
if (input.equals("print")) { StdOut.println(list.toString()); continue; }
if (input.charAt(0) == ('+')) { list.add(input.substring(1)); continue; }
if (input.charAt(0) == ('-')) { list.remove(input.substring(1)); continue; }
break;
}
}
}
For more LinkedList examples, your can check out the article.

Categories