I am trying to check whether linked list is palindrome using queue.
solve() function returns true if linked list is palindrome.Equating q.peek with Node value returns false even after values are equal.
Tried printing q.peek() returns LList$Node#7852e922.
I did google it says like Queue node value is in use in previous functional call, did not get much.
public class LList {
private Node head = null;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
public void push(int d) {
Node n = new Node(d);
n.next = head;
head = n;
}
public boolean solve(Node t, Queue q) {
if (t == null) {
return true;
}
q.add(t.data);
if (solve(t.next, q)) {
**System.out.println(q.peek());**//LList$Node#7852e922
if (q.peek().equals(t.data)) {
q.remove();
} else {
return false;
}
} else {
return false;
}
return true;
}
public static void main(String args[]) {
LList lList = new LList();
lList.push(5);
lList.push(4);
lList.push(3);
lList.push(4);
lList.push(5);
Queue<Integer> q = new LinkedList<Integer>();
System.out.println(lList.solve(lList.head, q));
}
}
As #Pramod said you adding a Node to queue here: q.dd(t)
In this method:
public boolean solve(Node t, Queue q) {
if (t == null) {
return true;
}
if (q == null) {
q = new LinkedList<Integer>();
}
q.add(t);
if (solve(t.next, q)) {
**System.out.println(q.peek());**//LList$Node#7852e922
if (q.peek().equals(t.data)) {
q.remove();
} else {
return false;
}
} else
return false;
return true;
}
Did you mean to q.add(t.data)?
You have declared Queue for Integer but you are trying to insert Node in the queue.
Change the comparison q.peek().equals(t.data) to q.peek().data == t.data and the type of queue to Queue<Node> q = new LinkedList<Node>()
Working code is(Comments added for the changes made):
public class LList {
//Made head static
private static Node head = null;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
public void push(int d) {
Node n = new Node(d);
n.next = head;
head = n;
}
//changed the parameter type to Queue<Integer>
public boolean solve(Node t, Queue<Integer> q) {
if (t == null) {
return true;
}
if (q == null) {
q = new LinkedList<>();
}
q.add(t.data);
if (solve(t.next, q)) {
System.out.println(q.peek()); //prints 5 4 3 4 5
//changed the comparison condition.
if (q.peek() == t.data) {
q.remove();
} else {
return false;
}
} else
return false;
return true;
}
public static void main(String args[]) {
LList lList = new LList();
lList.push(5);
lList.push(4);
lList.push(3);
lList.push(4);
lList.push(5);
System.out.println(lList.solve(lList.head, null));
}
}
Output:
5
4
3
4
5
true
Related
I have a big task to do as an exercise for Data Structures and algorithms, and part of it is to modify this tree data structure to print the tree in an alphabetical order.I won't post the whole task because it is huge. Im stuck on the last part which asks me to modify the given tree Data Structure to print the tree in an alphabetical order. I am stuck on it for couple of days and simple don't have any idea how to do it. Any help would be appriciated, thanks. My opinion is that i have to somehow modify the printTreeRecursive() method.
For example the current data structure will print a tree like this:
c: d c b a
(The first added child is printed last).
Where c: is the root and d c b a are his children
But im supposed to modify it to look like this:
c: a b c d
Here is the data structure:
public class SLLTree<E> implements Tree<E> {
// SLLNode is the implementation of the Node interface
class SLLNode<P> implements Node<P> {
// Holds the links to the needed nodes
SLLNode<P> parent, sibling, firstChild;
// Hold the data
P element;
public SLLNode(P o) {
element = o;
parent = sibling = firstChild = null;
}
public P getElement() {
return element;
}
public void setElement(P o) {
element = o;
}
}
protected SLLNode<E> root;
public SLLTree() {
root = null;
}
public Node<E> root() {
return root;
}
public Tree.Node<E> parent(Tree.Node<E> node) {
return ((SLLNode<E>) node).parent;
}
public int childCount(Tree.Node<E> node) {
SLLNode<E> tmp = ((SLLNode<E>) node).firstChild;
int num = 0;
while (tmp != null) {
tmp = tmp.sibling;
num++;
}
return num;
}
public void makeRoot(E elem) {
root = new SLLNode<E>(elem);
}
public Node<E> addChild(Node<E> node, E elem) {
SLLNode<E> tmp = new SLLNode<E>(elem);
SLLNode<E> curr = (SLLNode<E>) node;
tmp.sibling = curr.firstChild;
curr.firstChild = tmp;
tmp.parent = curr;
return tmp;
}
public void remove(Tree.Node<E> node) {
SLLNode<E> curr = (SLLNode<E>) node;
if (curr.parent != null) {
if (curr.parent.firstChild == curr) {
// The node is the first child of its parent
// Reconnect the parent to the next sibling
curr.parent.firstChild = curr.sibling;
} else {
// The node is not the first child of its parent
// Start from the first and search the node in the sibling list
// and remove it
SLLNode<E> tmp = curr.parent.firstChild;
while (tmp.sibling != curr) {
tmp = tmp.sibling;
}
tmp.sibling = curr.sibling;
}
} else {
root = null;
}
}
class SLLTreeIterator<T> implements Iterator<T> {
SLLNode<T> start, current;
public SLLTreeIterator(SLLNode<T> node) {
start = node;
current = node;
}
public boolean hasNext() {
return (current != null);
}
public T next() throws NoSuchElementException {
if (current != null) {
SLLNode<T> tmp = current;
current = current.sibling;
return tmp.getElement();
} else {
throw new NoSuchElementException();
}
}
public void remove() {
if (current != null) {
current = current.sibling;
}
}
}
public Iterator<E> children(Tree.Node<E> node) {
return new SLLTreeIterator<E>(((SLLNode<E>) node).firstChild);
}
void printTreeRecursive(Node<E> node, int level) {
if (node == null)
return;
int i;
SLLNode<E> tmp;
for (i = 0; i < level; i++)
System.out.print(" ");
System.out.println(node.getElement().toString());
tmp = ((SLLNode<E>) node).firstChild;
while (tmp != null) {
printTreeRecursive(tmp, level + 1);
tmp = tmp.sibling;
}
}
public void printTree() {
printTreeRecursive(root, 0);
}
public int countMaxChildren() {
return countMaxChildrenRecursive(root);
}
int countMaxChildrenRecursive(SLLNode<E> node) {
int t = childCount(node);
SLLNode<E> tmp = node.firstChild;
while (tmp != null) {
t = Math.max(t, countMaxChildrenRecursive(tmp));
tmp = tmp.sibling;
}
return t;
}
}
public interface Tree<E> {
// //////////Accessors ////////////
public Tree.Node<E> root();
public Tree.Node<E> parent(Tree.Node<E> node);
public int childCount(Tree.Node<E> node);
// //////////Transformers ////////////
public void makeRoot(E elem);
public Tree.Node<E> addChild(Tree.Node<E> node, E elem);
public void remove(Tree.Node<E> node);
// //////////Iterator ////////////
public Iterator<E> children(Tree.Node<E> node);
// //////Inner interface for tree nodes ////////
public interface Node<E> {
public E getElement();
public void setElement(E elem);
}
}
public class SLLTreeTest {
public static void main(String[] args) {
Tree.Node<String> a, b, c, d;
SLLTree<String> t = new SLLTree<String>();
t.makeRoot("C:");
a = t.addChild(t.root, "Program files");
b = t.addChild(a, "CodeBlocks");
c = t.addChild(b, "codeblocks.dll");
c = t.addChild(b, "codeblocks.exe");
b = t.addChild(a, "Nodepad++");
c = t.addChild(b, "langs.xml");
d = c;
c = t.addChild(b, "readme.txt");
c = t.addChild(b, "notepad++.exe");
a = t.addChild(t.root, "Users");
b = t.addChild(a, "Darko");
c = t.addChild(b, "Desktop");
c = t.addChild(b, "Downloads");
c = t.addChild(b, "My Documents");
c = t.addChild(b, "My Pictures");
b = t.addChild(a, "Public");
a = t.addChild(t.root, "Windows");
b = t.addChild(a, "Media");
t.printTree();
t.remove(d);
t.printTree();
System.out.println("The maximum number of children is "
+ t.countMaxChildren());
}
}
As I see, my initial suggestion is good-enough for the asker and other commenters as well. So, as this is a studying task, I will not write code as an answer (I would take all the fun, wouldn't I?). I will share some important checkpoints to reach in the thought process, which, if reached should lead to the solution:
we need a Collection
we need to use a breadth-first traversing (printTreeRecursive is a good example)
we need to look at the while cycle of printTreeRecursive, as it is key to reach a traversing
whenever we reach a node, we should insert sort the node into the collection
after the traversing, we iterate the Collection and print out its elements
My problem is in the add method. I think I know what I want it to do but I can't figure out what type of loop I should use to look through the list. As you can see I started to make a if else loop but I couldn't figure out what I should use as the counter. I'm pretty sure I have the right logic in dealing with the add but I feel like I'm not quite there yet. I was thinking of using compareTo in some fashion.
import java.util.*;
public class OrderedLinkedList<E extends Comparable<E>>
{
private Node topNode;
private class Node
{
private E data;
private Node nextNode;
public Node(E data)
{
this.data = data;
nextNode = null;
}
}
public OrderedLinkedList()
{
topNode = null;
}
public boolean empty()
{
if(topNode == null)
return true;
return false;
}
public String toString()
{
String myString = "";
Node nextNode = topNode;
while(nextNode != null)
{
myString = topNode + " -> " + nextNode;
nextNode = topNode.nextNode;
}
return myString;
}
public void add(E data)
{
Node myNode = new Node(data);
Node priorNode = topNode;
Node currentNode = topNode;
if(___)
{
priorNode = currentNode;
currentNode = currentNode.nextNode;
}
else
{
priorNode.nextNode = myNode;
myNode.nextNode = currentNode;
}
}
}
Since you don't typically know the length of a linked list until you've walked down it, the usual thing would be to use a while loop (as you've done in your toString() method)
Perhaps using a doubly linked list would be more beneficial. Consider the following alterations to your class:
import java.util.*;
public class OrderedLinkedList<E extends Comparable<E>>
{
private Node head;
private Node tail;
private class Node
{
private E data;
private Node nextNode;
private Node prevNode;
public Node(E data)
{
this.data = data;
nextNode = null;
prevNode = null;
}
public void setNext(Node node)
{
this.nextNode = node;
}
public Node getNext()
{
return this.nextNode;
}
public void setPrev(Node node)
{
this.prevNode = node;
}
public Node getPrev()
{
return this.prevNode;
}
public E getData()
{
return this.data;
}
public int compareTo(Node that) {
if(this.getData() < that.getData())
{
return -1;
}
else if(this.getData() == that.getData()
{
return 0;
}
else
{
return 1;
}
}
}
public OrderedLinkedList()
{
head = new Node(null);
tail = new Node(null);
head.setNext(tail);
tail.setPrev(head);
}
public boolean empty()
{
if(head.getNext() == tail)
{
return true;
}
return false;
}
public void add(E data) {
Node tmp = new Node(data);
if(this.empty()) {
this.addNodeAfterNode(tmp, head);
} else {
Node that = head.getNext();
// this while loop iterates over the list until finding the correct
// spot to add the new node. The correct spot is considered to be
// when tmp's data is >= that's data, or the next node after 'that'
// is tail. In which case the node is added to the end of the list
while((tmp.compareTo(that) == -1) && (that.getNext() != tail)) {
that = that.getNext();
}
this.addNodeAfterNode(tmp, that);
}
}
private void addNodeAfterNode(Node addNode, Node afterNode)
{
addNode.setNext(afterNode.getNext());
afterNode.getNext().setPrev(addNode);
afterNode.setNext(addNode);
addNode.setPrev(afterNode);
}
}
My java class comps up with a NullPointerException.Please help!
The error messages:
java.lang.NullPointerException at
RandomizedQueue.dequeue(52 line) at
RandomizedQueue$IndependantIterator.next (88 line) at
RandomizedQueue.main (104)
I have signed the line number in the end of the error code line.
import java.util.Iterator;
public class RandomizedQueue<Item> implements Iterable<Item> {
private int number=0;
private Node first=null;
private Node end=null;
private class Node {
Item item;
Node next=null;
Node last=null;
}
private Node Random() {
double r = Math.random();
int n = (int) (r*number);
if(n==0) n=1;
Node ob=first;
for(int i=0;i<(n-1);i++) {
ob = ob.next;
}
return ob;
}
public RandomizedQueue() {
Node empty=new Node();
}
public boolean isEmpty() {
return number==0;
}
public int size() {
return number;
}
public void enqueue(Item item) {
if(item==null) throw new NullPointerException();
number++;
if(first==null) {
first = new Node();
end = first;
first.item = item;
}
else {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
oldfirst.last = first;
}
}
public Item dequeue() {
Node ob=Random();
Item back=ob.item;
if(ob==end) {
end = ob.last;
ob.last.next=null; //52 line
}else if(ob==first) {
first=first.next;
first.last=null;
}
else {
ob.last.next=ob.next;
ob.next.last=ob.last;
}
return back;
}
public Node sample() {
return Random();
}
public Iterator<Item> iterator() {
return new IndepentRandomIterator();
}
private class IndepentRandomIterator implements Iterator<Item> {
private RandomizedQueue<Item> iq = new RandomizedQueue<Item>();
Node scan = first;
public IndepentRandomIterator() {
while(scan != null) {
iq.enqueue(scan.item);
scan=scan.next;
}
}
public boolean hasNext() {
return iq.number >0;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if(iq.number==0) throw new java.util.NoSuchElementException();
return iq.dequeue(); //88
}
}
public static void main(String[] args) {
RandomizedQueue<String> test = new RandomizedQueue<String>();
test.enqueue("Luo");
test.enqueue("Jiebin");
test.enqueue("is");
test.enqueue("genious");
test.dequeue();
test.dequeue();
StdOut.println("Is it empty?"+test.isEmpty());
StdOut.println("Size: "+test.size());
StdOut.println("A sample: "+test.sample());
Iterator<String> it = test.iterator();
while(it.hasNext()) {
String s = it.next(); //104
}
}
}
It's because ob.last is null. The only time that end is set is when item is first in enqueue(). And last is never set there. In dequeue(), it goes to the if block if ob == end. Since end.last == null, therefore ob.last == null too and ob.last.next will throw NPE.
I am a newbie in Java and OOP, the previous language that I've learned being C.
I am trying to create a Linked List that extends AbstractList and that allows the usage of Collections.sort() function. The problem is that when I call the Collections.sort() function, I get a nullPointerException. My guess is that the exception resides from the fact that the last node in my list is a null one (so I can know where the list ends).
class Node
{
Object o;
Node next;
public Node(Object n)
{
o = n;
next = null;
}
}
class LinkList extends AbstractList
{
Comparator c;
public Node head, last;
public LinkList(Comparator c)
{
this.c = c;
head = null;
last = null;
}
#Override
public boolean add(Object a)
{
Node t = new Node(a);
if(last == null)
{
head = t;
last = t;
last.next = null;
}
else //thanks, hyde
if(last != null)
{
last.next = t;
last = t;
last.next = null;
}
return true;
}
#Override
public Object get(int a)
{
Node it = head;
int contor = 0;
while(it!=null && contor<a)
{
it = it.next;
}
if(it!=null)
{
return it;
}
else
return null;
}
#Override
public Object set(int i, Object a)
{
Node it = head;
int contor = 0;
Node aux;
while(it!=null && contor<i)
{
it = it.next;
}
if(it!=null)
{
aux = it;
it.o = a;
// Collections.sort(this,c);
return aux;
}
else
return null;
}
#Override
public int size()
{
Node it = head;
int contor = 0;
while(it!=null)
{
contor++;
it = it.next;
}
return contor;
}
#Override
public int indexOf(Object a)
{
Node it = head;
int contor = 0;
while(it!=null && it.o.equals(a)==false)
{
it = it.next;
contor++;
}
if(it!=null)
{
return contor;
}
else
return -1;
}
}
public class Test
{
public static void main(String args[])
{
LinkList lista = new LinkList(new Comparator(){
#Override
public int compare(Object o1, Object o2)
{
int s1 = (int) o1;
int s2 = (int) o2;
return s2-s1;
}
});
lista.add(2);
lista.add(3);
Collections.sort(lista); //this is line 156
System.out.println(lista.size());
}
}
Basically, I add two elements and I try to sort the list and I get the nullPointerException. It feels very frustrating, because I have no control over the sort function.
Exception in thread "main" java.lang.NullPointerException
at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:157)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
at java.util.Arrays.sort(Arrays.java:472)
at java.util.Collections.sort(Collections.java:155)
at Ex6.main(Ex6.java:156)
Java Result: 1
You are missing contor++ in the loop inside the get method so it always returns null.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I implement a Linked List in Java?
We know there is no pointers in java. Then what is the best way to build the link list in java?
The best way is to not build it. Java already has a LinkedList class amongst its rather large selection of collection classes.
You would be better off using what the language/library already provides.
You have an object that essentially contains two variables, no methods (bare minimum; however, you could have methods if you wanted). Something like:
class Link
{
int data;
Link next;
}
Then you create a new Link like any other object. Set the data to the data you want a node to hold. Then set the Link node to the node that it will be "pointing" to (or null if it doesn't point to another one).
Note: you can also have a previous node (which points to the previous node) if need be.
try having this code.
public class Main {
public static void main(String[] args) {
LinkedList theList = new LinkedList();
LinkedListIterator theItr;
theItr = theList.zeroth();
printList(theList);
for (int i = 0; i < 10; i++) {
theList.insert(new Integer(i), theItr);
printList(theList);
theItr.advance();
}
System.out.println("Size was: " + listSize(theList));
}
public static int listSize(LinkedList theList) {
LinkedListIterator itr;
int size = 0;
for (itr = theList.first(); itr.isValid(); itr.advance())
size++;
return size;
}
public static void printList(LinkedList theList) {
if (theList.isEmpty())
System.out.print("Empty list");
else {
LinkedListIterator itr = theList.first();
for (; itr.isValid(); itr.advance())
System.out.print(itr.retrieve() + " ");
}
System.out.println();
}
}
class LinkedList {
public LinkedList() {
header = new ListNode(null);
}
public boolean isEmpty() {
return header.next == null;
}
public void makeEmpty() {
header.next = null;
}
public LinkedListIterator zeroth() {
return new LinkedListIterator(header);
}
public LinkedListIterator first() {
return new LinkedListIterator(header.next);
}
public void insert(Object x, LinkedListIterator p) {
if (p != null && p.current != null)
p.current.next = new ListNode(x, p.current.next);
}
public LinkedListIterator find(Object x) {
ListNode itr = header.next;
while (itr != null && !itr.element.equals(x))
itr = itr.next;
return new LinkedListIterator(itr);
}
public LinkedListIterator findPrevious(Object x) {
ListNode itr = header;
while (itr.next != null && !itr.next.element.equals(x))
itr = itr.next;
return new LinkedListIterator(itr);
}
public void remove(Object x) {
LinkedListIterator p = findPrevious(x);
if (p.current.next != null)
p.current.next = p.current.next.next; // Bypass deleted node
}
private ListNode header;
}
class LinkedListIterator {
LinkedListIterator(ListNode theNode) {
current = theNode;
}
public boolean isValid() {
return current != null;
}
public Object retrieve() {
return isValid() ? current.element : null;
}
public void advance() {
if (isValid())
current = current.next;
}
ListNode current;
}
class ListNode {
public ListNode(Object theElement) {
this(theElement, null);
}
public ListNode(Object theElement, ListNode n) {
element = theElement;
next = n;
}
public Object element;
public ListNode next;
}