Display letters in reverse order of stacks - java

I wrote this code of stacks using a linked list but I am having a problem with the code it prints the letters in reverse order without creating a function to display the letters in reverse order
class SimpleLinkedListStack2 implements SimpleStack ,Iterable {
static class ListNode<T> {
public T value;
public ListNode<T> next;
public ListNode(T value, ListNode<T> next) {
this.value = value;
this.next = next;
}
}
private ListNode<T> head = null;
private int count = 0;
public Iterator<T> iterator() {
return new Iterator<T>() {
private ListNode<T> next = head;
#Override
public boolean hasNext() {
return next != null;
}
#Override
public T next() {
if (next == null)
throw new NoSuchElementException();
T value = next.value;
next = next.next;
return value;
}
};
}
#Override
public void push(T value) {
head = new ListNode<>(value, head);
count++;
}
#Override
public T pop() throws Exception {
if (count == 0) {
throw new Exception("Stack is empty");
}
T value = head.value;
head = head.next;
count--;
return value;
}
#Override
public T peek() throws Exception {
if (count == 0) {
throw new Exception("Stack is empty");
}
return head.value;
}
}
this is the main class
public class main {
public static void main(String[] args) {
SimpleLinkedListStack2 <String>stack2= new SimpleLinkedListStack2<>();
stack2.push("a");
stack2.push("b");
stack2.push("c");
stack2.push("d");
stack2.push("e");
for (String letters : stack2){
System.out.println(letters);
}
}
}
the out but is
e
d
c
b
a
because I need to make a function to display the letters in reverse order in the class SimpleLinkedListStack2

Just walk through your code:
stack2.push("a");
This changes your stack's head from null to a node that has no next and whose value is "a". Your stack is now: -> ["a", -> null], where -> is 'pointing at object'.
stack2.push("b");
And now your stack is -> ["b", -> ["a", -> null]]: You create a new ListNode object for "b", and update its 'next' pointer to be what head was, and then head points at this newly created thing.
Thus, of course, if you then iterate through it, you get the last thing you added ("b" here), first.
Hence, your code pritns e d c b a - it's what you put in the list, in reverse order, because that's what you programmed, and that's what stacks are (they are 'Last in, First Out' - the last thing you put it is the e, and that's the first thing that comes out, as per the design!
But I want to print in the same order I put the items in!
This is a so-called 'singly linked list', meaning, any given LinkedNode knows its next node, but does not know its previous node. You cannot in-place reverse-walk-through a singly linked list - what you want is not possible without drastic steps.
For example, you could make an entirely new stack, just by iterating through this stack, which naturally ends up with the newly created stack being the exact reverse of the original. And then print that reversed stack, and then toss it away (java is garbage collected; that part happens automatically). There is no 'easy' solution / no solution that takes no memory. You could also just build the string out, and then reverse that instead.
Perhaps that's the point of this homework exercise, to make you think about how these LinkedNode objects relate to each other in memory. Get out a pad of paper and go sketch it out. Boxes and arrows. You'll figure it out.

Related

Question about Conceptual Understanding for Circular doubly linked list in Java

I am a beginner coder in java and in general and I wanted to ask for some help. I am doing an assignment in which I am supposed to make a CircularLinkedList which is like a DoublyLinkedList. But for CircularLinkedList am not allowed to have a head or a tail. Instead, I have a pointer to one of the nodes in the CircularLinkedList. So, to my understanding from basic LinkedList, the head node is where we would implement our series of Singly LinkedList.
I have made a DoubleNode pointer as a global variable that will at first point at the first node when we create a circular linked list. when I construct a CircularLinkedList that is empty.
My question is: Should this DoubleNode pointer point to null within the constructor or should I just create a new node and make them point to null with not value to claim its empty?
I am posting my code for better understanding my concept
public class CircularLinkedList<T> {
DoubleNode pointer; //create a double node of pointer [/| no data |\]
int lengthoflinkedlist = 0;
private class DoubleNode<T> { //create a DoubleNode class to understand how nodes would look in the circular linked list
private DoubleNode prev;
private T data;
private DoubleNode next;
// Now we input our functions into the class or methods as they call it
public DoubleNode(){ //constructors for bas node.
this.prev = null;
this.next = null;
}
public DoubleNode(T data) {
this.prev = null;
this.data = data;
this.next = null;
}
public DoubleNode(DoubleNode P, T data, DoubleNode N){
this.prev = P;
this.data = data;
this.next = N;
}
}
public CircularLinkedList() {
// pointer
DoubleNode A = new DoubleNode(); // creates a node with nothing and pointers to null;
}
public CircularLinkedList(int initSize, T initValue) { //constucting a circular linked list
// TODO implement me
//initSize means the size of linkedlist
//initValue means the value of data T in the nodes.
if(initSize == 0) { //throw error as length 0 means linkedlist is empty
System.out.println("The linked list with size 0 means it is an empty linkedlist with a Pointer pointing to Nothing");
}
else {
DoubleNode check = this.pointer;
for(int lengthoflinkedlist = 0; lengthoflinkedlist < initSize - 1; lengthoflinkedlist++) {
DoubleNode A = new DoubleNode(this.pointer.next,initValue,this.pointer.prev);
}
}
}
public void moveForward() {
// TODO implement me
}
public void moveBackward() {
// TODO implement me
}
public T getValue() {
// TODO implement me
return null;
}
/**
* #return the previous value of the updated node
*/
public T setValue(T value) {
// TODO implement me
return null;
}
public void addBefore(T value) {
// TODO implement me
}
public void addAfter(T value) {
// TODO implement me
}
/**
* #return the previous value of the removed node
*/
public T removeBefore() {
// TODO implement me
return null;
}
/**
* #return the previous value of the removed node
*/
public T removeAfter() {
// TODO implement me
return null;
}
public boolean isEmpty() {
// TODO implement me
return true;
}
}
I am still implementing my class and constructors atm so i need help based on that
My question is, first of, I have made a DoubleNode pointer as a global variable that will at first point at the first node when we create a circular linked list.
I can't see a "global" variable. I can see an instance variable called pointer ... which I assume is what you are talking about.
Should this DoubleNode pointer point to null within the constructor or should I just create a new node and make them point to null with not value to claim its empty?
Actually, you can do it either way.
One way would be to have an empty list represented as a CircularLinkedList with a null value in the pointer field.
Another way would be to have an empty list represented as a CircularLinkedList with a pointer that refers to a DoubleNode with null data.
I think that the first approach will be simpler. Either way you need special case code for when the list is empty.
You wrote:
But for CircularLinkedList am not allowed to have a head or a tail.
I would expect this to be true since a circle doesn't have a concrete beginning or end. In a circle, they are arbitrary. Unlike a conventional list, when a circular list is empty, the head (beginning node) is whatever you want it to be. The trick is how you calculate the end. This is important because at some point you need to calculate if the circular list is full.
Assume this array is your "circular list". You could literally decide to make your first insertion right in the middle (index 2). In this case, the "tail" will be your starting index minus 1 (i.e. 1). The problem is, how do you wrap around when you reach index 4 to go to index 0 for the next insertion?
To increment an index in a wrap around manner, you need to use the following formula: index = (index + 1) % N where N is the size of the list; in this case 5.
Now, how do you know your circular list is full? This is actually pretty simple. Before you insert, you will "peek" to the next location to see if there is something there already. If the next slot in your circular list is empty, you can then insert. ON the other hand, if the next slot is full, your list is full.
Last, you need to consider going in reverse order (i.e. to get previous node). The technique is the same. First, you will "peek" the previous index to see if there something there. If the previous slot has a node, you can freely do what you need with it.
The rest of things to considered are unknown to me because your post is not very specific.

Constructor Node cannot be applied to given types while working with nodes

I am working on a code that puts new elements on MyStack if they are unique. I had to copy and paste the node starting code, so I'm having a bit of trouble with an issue. I keep getting two error messages, even after trying various workarounds and I'm not really understanding why. I've even tried using some helper functions I've previously made that have worked before so I'm extra confused.
The two errors I consistently get are:
-cannot infer type arguments for MyStack.Node (actual and formal arguments differ in length)
-constructor node cannot be applied to given types. Required, no arguments, found: anything,
Here's my code:
public class MyStack<Anything>
{
private Node first, last;
private class Node<Anything>
{
Anything item;
Node next;
}
public boolean contains(Anything value)
{
for (Node curr = first; curr != null; curr = curr.next)
{
if (value.equals(curr.item)) {
return true;
}
}
return false;
}
public void add(Anything value)
//method that adds a new value to the end of the list
//COMPLETE
{
Node temp = first;
while(temp.next!=null){ //finds the end
temp=temp.next;
}
temp.next=new Node(value, null); //assigns new value
}
public void enqueue(Anything info){
if (this.contains(info)==true) { //if the info is already present
System.out.println("the stack already contains this value");
return;
}
//if we actually need to add the info
if (first == null) { //if there is nothing in the stack
Node temp= first;
first = new Node<>(info,temp);
first = temp;
return;
}
if (first != null) { //if there is already stuff
Node temp = first;
while (temp.next == null)
{ Node newNode= new Node<>(info, temp);
temp.next = newNode;
}
return;
}
}
}
As #Andreas already pointed out, Node needs a constructor.
There are a few other flaws in your Code:
Use Generics
With your Code, you can only store Objects of the class Anything, what strongly limits its reusability. Use a generic instead and you can reuse this class for many more purposes.
Linked List
I suggest, you use the paradigm of a double-linked-list. That way you do not need to find the last Node to add something to the Stack. Node now has a pointer to its previous and next element.
Use the last Object
You have the object last but never use it. To find out, whether the current object is the last one you compare the value to null. This has the effect, that storing a null value will break your List. Instead compare to the Object last, this object is unique and guarantees you, that you are at the end of the list. Both first and last are Nodes that do not contain a value and are simply used to mark the start/end of your List.
Adding elements
Using the changes above, the code in the Method enqueue(T value) becomes significantly simpler: You just check whether contains(value) and decide whether you add the value to the List or not.
All these changes applied result in following code:
public class MyStack<T extends Object> {
private Node first, last;
public MyStack() {
first = new Node(null, null, null);
last = new Node(null, null, first);
first.next = last;
}
private class Node {
T item;
Node next;
Node previous;
public Node(T item, Node next, Node previous) {
this.item = item;
this.next = next;
this.previous = previous;
}
}
public boolean contains(T value) {
for (Node curr = first.next; curr != last; curr = curr.next) {
if (value.equals(curr.item)) {
return true;
}
}
return false;
}
/**
* method that adds a new value to the end of the list
*/
public void add(T value)
{
Node secondLast = last.previous;
Node added = new Node(value, last, secondLast);
secondLast.next = added;
last.previous = added;
}
/**
* only adds value if it is not already contained by the Stack
*/
public void enqueue(T value) {
if (this.contains(value) == true) { // if the info is already present
System.out.println("the stack already contains this value");
}
else {
add(value);
}
}
public static void main(String[] args) {
MyStack<String> test = new MyStack<>();
test.add("foo");
test.add("bar");
test.add("baz");
System.out.println(test.contains("bar"));
System.out.println(test.contains("new"));
test.enqueue("baz");
test.enqueue("MyStack");
}
}
Naming
As you may have noticed, in my explanation I called this class a List. This is because it fulfills more of the characteristics of a List. A Stack usually only provides the methods push to put something at the top of the Stack and pop to remove and return the topmost Object. Optionally peek can return the topmost Object, without removing it from the Stack.
Also consider renaming the method enqueue: enqueue is used in Queues (obviously) and Queues do not forbid to add two equal Objects. So the name is misleading. I would call this method something like addIfNotContaining.
In my Opinion you should name this class to be a List and add a method get(int i) to get a specific element at a position. Naturally adding some other methods like size ect. to comply with a standard List. But I assume you already had, but did not post them because they are not related to your problem.
Multithreading
This Class is far from threadsave. But I let you figure out yourself how to make it threadsave if needed.

How to find the first value in a linked list?

I have a linked list I'm given and I need to find the first value in the list via a getFirst method.I need to display an error message and quit the program if the value is null. The linked list is already given to me link so:
class MyLinkedList
{
private class Node // inner class
{
private Node link;
private int x;
}
//----------------------------------
private Node first = null; // initial value is null
//----------------------------------
public void addFirst(int d)
{
Node newNode = new Node(); // create new node
newNode.x = d; // init data field in new node
newNode.link = first; // new node points to first node
first = newNode; // first now points to new node
}
//----------------------------------
public void traverse()
{
Node p = first;
while (p != null) // do loop until p goes null
{
System.out.println(p.x); // display data
p = p.link; // move p to next node
}
}
}
//==============================================
class TestMyLinkedList
{
public static void main(String[] args)
{
MyLinkedList list = new MyLinkedList();
list.addFirst(1);
list.addFirst(2);
list.addFirst(3);
System.out.println("Numbers on list");
list.traverse();
}
}
Here's what I tried out for the method:
public static Node getFirst(Node list)
{
if (list == null)
{
System.out.println("Error!");
System.exit(1);
}
return MyLinkedList.first;
}
I know this isn't exactly right, we just started this in my class so I'm having trouble understanding what's going on with it. Thank you!
I think you should look at https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html and get an idea for the behavior of a linked list initially. Once you have an idea on how it behaves, you can think about how to add functionality around it. Right now you just have a single method which you call more than you should. What also might help is to create an interface and document it so you know what each method should do.
You should check that first isn't null in order to do what you describe in the question. Also, it is kind of weird that the first node autoreferences itself because usually it is left in null until you add another node
notice that the first value is linked to the first Node with is null. Then you have to check two things
Node == null (you got this)
Node.next == null (you have to do this)
When Node.next == null. It means that Node is first value because it is linked to the initial Node with is null.
Then you have
public static Node getFirst(Node list)
{
// if the list is empty
if (list == null)
{
System.out.println("Error!");
System.exit(1);
} else if(list.link == null) {
// this is the first value!
return list;
} else {
// keep searching recursive with the next Node
return getFirst(list.link);
}
}
The class MyLinkedList in your question follows the pattern of a stack data structure(At the time when i am writing this answer). That is: ever time you add a new element, the new element replaces the previously added element as the first element.
I guess you want to get 1 as your first element, if you have added elements 1,2,3 in that order. Correct me if i am wrong.
In that case your linked list and it's retrieval should be like this:
(Note: i have avoided private vars , public getter , settter , etc; to make code easily readable. But readers should add them.)
class Node{ int x; Node next; }
class LinkedList
{ Node head,tail;
void add(int y)
{ Node node = new Node();
node.x=y;
if(head==null)
head = tail = node;
else
tail = tail.next = node;
}
int getFirst()
{ if(head!=null)
return head.x;
else
throw new java.util.NoSuchElementException("List is empty");
}
}
If you look at java.util.LinkedList, you will find methods that are conventionally used in linked lists. If this is not a homework question, then i suggest you do not reinvent the wheel. Just use the existing libraries.
If you have to use the stack data structure, and you cannot change it, then i suggest you have to change your getFirst() like this:
int getFirst()
{ if(tail!=null)
return tail.x;
else
throw new java.util.NoSuchElementException("List is empty");
}
If you not allowed to add Node tail in your code, then your getFirst() will look like this:
int getFirst()
{ if(head==null)
throw new java.util.NoSuchElementException("List is empty");
Node node = head;
while(node.next!=null)
node=node.next;
return node.x;
}

Java LinkedList adding multiple nodes

my question is in my main method, how to add multiple nodes to the linked list....What I have now with first, node2, node3..I thought was adding those nodes but I realized I don't think I'm actually doing anything with those nodes and their values, right? How do I use setData() and setNext() to add all of those nodes. Does that make sense?
ListNode<String> node4 = new ListNode<String>("Fourth", null);
ListNode<String> node3 = new ListNode<String>("Third", node4);
ListNode<String> node2 = new ListNode<String>("Second", node3);
ListNode<String> first = new ListNode<String>("First", node2);
If the above sets up the values how do I add them all?
Do I then need to set the data and next for each one of these? (This seems redundant since I seem to be setting up the value of each nodes data and next in the constructor above?)
first.setData("first");
first.setNext(node2);
node2.setData("Second");
node2.setNext(node2);
//.....
I'm trying to add all of the above nodes so I can test my addLast() method by adding a new node. However, when I call my addLast() method in main as you can see below the only thing that's printed is that addLast() value I added (and first if I call addFirst()).
Test Class
public class LinkedListDriver
{
public static void main(String[] args) {
//List<String> list = new LinkedList<String>(); //comment out this line to test your code
SinglyLinkedList<String> list = new SinglyLinkedList<String>(); //remove comment to test your code
ListNode<String> node4 = new ListNode<String>("Fourth", null);
ListNode<String> node3 = new ListNode<String>("Third", node4);
ListNode<String> node2 = new ListNode<String>("Second", node3);
ListNode<String> first = new ListNode<String>("First", node2);
ListNode value = new ListNode("First", new ListNode("Second", new ListNode("Third", null)));
//I've been messing around with this but
list.addFirst(first.getData());
list.addFirst("Second");
list.addLast("Fifth");
list.printList();
}
}
I didn't add my other two classes because I didn't think it was relevant but if you'd like to see it let me know. I'm very new this is only my second class and it's online and is poorly constructed class, please be nice lol
SinglyLinkedList class
//This class implements a very simple singly-linked list of Objects
public class SinglyLinkedList<E>
{
ListNode<E> first; // first element
public SinglyLinkedList() {
first = null;
}
public E getFirst() {
if (first == null) {
throw new NoSuchElementException();
} else
return first.getData();
}
public void addFirst(E value) {
first = new ListNode<E>(value, first);
}
// Methods below implemented by you. Note: while writing methods, keep in mind
// that you might be able to call other methods in this class to help you - you
// don't always need to start from scratch(but you'll have to recognize when)
public void addLast(E value) {
ListNode<E> temp = first;
//If list is empty make new node the first node.
if (temp == null) {
first = new ListNode <E>(value, null);
first.setNext(null);
}//Otherwise loop to end of list and add new node.
else {
while (temp.getNext() != null) {
temp = temp.getNext();
}
temp.setNext(new ListNode<E>(value, null));
}
}//end addLast
// throws an exception - you decide when and which one
public E getLast() {
ListNode<E> temp = first;
if (temp == null) {
throw new NullPointerException("There are no elements in this list to get.");
} else {
while (temp.getNext() != null) {
temp = temp.getNext();
}
return temp.getData();
}
}
// throws an exception - you decide when and which one
public E removeFirst() {
if (first == null) {
throw new NullPointerException("There are no elements in this list to remove.");
}
ListNode<E> tempRemove = first;
return null; //just so it'll compile
}
// throws an exception - you decide when and which one
public E removeLast() {
return null; //just so it'll compile
}
// return the number of elements in the list
public int size() {
return 0; //just so it'll compile
}
// return true if o is in this list, otherwise false
public boolean contains(E obj) {
return true; //just so it'll compile
}
public void printList(java.io.PrintStream out) {
if (first == null) {
System.out.println("The list is empty");
}
ListNode<E> current = first;
while (current != null) {
System.out.println(current.toString());
current = current.getNext();
}
}
public String toString() {
String s = "[";
ListNode<E> current = first;
//write code to traverse the list, adding each object on its own line
while (current.getNext() != null) {
current = current.getNext();
}
s += "]";
return s;
}
// OPTIONAL: just for fun...and a challenge
public void reverse() {
}
}
ListNode class is your basic getNext setNext, getData setData....
A couple of points, mostly summarizing the comments:
You shouldn't work with ListNode objects in main() at all - that should be the job of the SinglyLinkedList class. ListNode doesn't even need to be visible to the rest of the code, it could be a nested class in SinglyLinkedList. You should only be exchanging the data objects (Strings in this case) with SinglyLinkedList.
If you want to test for example the addLast() method, you could start with an empty list and repeatedly call list.addLast(), as Shane mentions in his answer. That way you will make sure it works when the list is empty as well as nonempty.
SinglyLinkedList<String> list = new SinglyLinkedList<String>();
list.addLast("first");
list.addLast("second");
list.addLast("third");
list.printList(System.out);
As for adding multiple nodes in a single call - this linked list doesn't have a method for that. You could add a method for adding all elements of an array for example, but you can just call addLast() sequentially with the same effect. You can create some helper method in the main class to populate the list in this way, if you want to start with some base data for testing other methods.
As a side note: if printList() takes java.io.PrintStream out as argument, you should use it instead of System.out. That is
out.println(...)
instead of
System.out.println(...)
Also, it's better to throw NoSuchElementException rather than NullPointerException as an indication that the requested element doesn't exist.
If you want a convenient way to populate the list, you could have something like this in your main class:
static <E> void addToList(SinglyLinkedList<E> list, E... values) {
for (E value : values) {
list.addLast(value);
}
}
and use it like this:
SinglyLinkedList<String> list = new SinglyLinkedList<String>();
addToList(list, "first", "second", "third");
What are you trying to do? If you're attempting to populate the linked list, all you need to do is continually call list.addLast, which will take a single parameter (the data in the new node you're adding), and deal with creating the new node and placing it in the back of the list.
You shouldn't need to create any nodes in your main, I'm assuming, as they are generally handled entirely by the linkedlist class.

Get Exception in thread "main" java.lang.NullPointerException with LinkedList

Simple Linked List
public class List_manager {
Entry first;
Entry last;
public void add(String el) {
if (isEmpty()) { first=new Entry(el); last=first; return; }
new Entry(el,last);
}
public String get() {
Entry temp=first;
first=first.next;
return temp.data;
}
public boolean isEmpty() {
return first==null;
}
private class Entry {
String data;
Entry next;
public Entry(String data,Entry to) {
this.data=data;
to.next=this;
to=this;
}
public Entry(String data) {
this.data=data;
}
}
}
#The main class#
I added 3 element and list contains only 2... why?
public class Main {
public static void main(String[] args) {
List_manager l=new List_manager();
l.add("1");
l.add("2");
l.add("3");
System.out.println(l.get());
System.out.println(l.get()); // Why here output: "3"??
System.out.println(l.get()); // here is an error occurs
}
}
I really don`t get why list contains 2 elements?
Why it ignores 2nd added element?
to=this; This sentence have no influence on variable 'last', because veriable 'to' is formal parameter, while variable 'last' is actual parameter. So, when you executed this sentence "to = this;" the value of
variable 'last' was not changed to next.That's mean variable 'last' always pointed to the first element.
my change is : new Entry(el,last); --> last = new Entry(el,last);
Things look better.
Think about what your get method is doing. You already noticed some aberrant behavior with it.
public String get() {
Entry temp=first;
first=first.next;
return temp.data;
}
What happens the first time I call this?
temp gets whatever first is pointing to
first is moved to its next element (RED FLAG)
temp's data is returned...
One problem is that you're moving your head reference around - this is a bad idea, since it means that you can never access the true first element in your list ever again.
Now on its own, even with this implementation, you should still be able to get the first element.
The above was just a red herring - although you should not be moving your head pointer around. This is the real problem. What happens on subsequent add calls to your list?
public void add(String el) {
if (isEmpty()) {
first = new Entry(el);
last = first;
return;
}
new Entry(el,last);
}
Only the first element inserted and the last element inserted are respected. All other entries after next are overwritten.
I suggest that you use a debugger to figure this one out, as it stems from a misunderstanding of a good approach to do this. You only want to insert things through your tail pointer once you have one element. Doing this through object creation only causes heartache and confusion.
For posterity, I'll leave you with a sample, verbatim implementation I wrote for a singly linked list implementation I did a while back. It describes a more viable approach to inserting into a list.
public void insert(E data) {
Node<E> candidate = new Node<>(data);
if(head == null) {
head = candidate;
tail = head;
} else {
tail.setNext(candidate);
tail = tail.getNext();
}
size = size + 1;
}

Categories

Resources