I am struggling to figure this out - I need to implement a method:
public int remove(int n)
where I remove the top most n entries from my stack. Any suggestions on where I can start to tackle this would be greatly appreciated.
Here is the code provided where I need to implement this remove() method.
public class LinkedStack<T> implements StackInterface<T>
{
private Node topNode; // references the first node in the chain
public LinkedStack()
{
topNode = null;
} // end default constructor
public void push(T newEntry)
{
Node newNode = new Node(newEntry, topNode); topNode = newNode;
} // end push
public T peek()
{
T top = null;
if (topNode != null)
top = topNode.getData();
return top;
} // end peek
public T pop()
{
T top = peek();
if (topNode != null)
topNode = topNode.getNextNode();
return top;
} // end pop
public boolean isEmpty() {
return topNode == null;
}
public void clear() {
topNode = null;
}
private class Node
{
private T data; // entry in stack
private Node next; // link to next node
private Node(T dataPortion)
{
this(dataPortion, null);
} // end constructor
private Node(T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode;
} // end constructor
private T getData()
{
return data;
} // end getData
private void setData(T newData)
{
data = newData;
} // end setData
private Node getNextNode()
{
return next;
} // end getNextNode
private void setNextNode(Node nextNode)
{
next = nextNode;
} // end setNextNode
} // end Node
} // end LinkedStack
The trivial solution is just to call this.pop() n times. For this, you need to use a loop.
Seems like your homework, so I'm not going to show a code example.
Related
I am having trouble doing a homework assignment involving stacks and nodes in Java. I understand the concept of Stacks but am confused with Nodes. The assignment is to make a program using Stacks (Not java.util.Stack) that checks a mathematical expression for correct pairs of (), [], and {}s. We already have the Node program.
So basically my problem is I would like some help completing the Push Method of my PStack class.
PStack.java
class PStack {
private Node top;
public PStack() {
top=null;
}
public boolean isEmpty() {
return top==null;
}
public int pop() {
Node top1 = top;
top = top.getNext();
return top1.getData();
}
public void push(Node n) {
}
public int peek() {
return top.getData();
}
}
Node.java
public class Node {
private int data;
private Node nextnode;
public Node(int intial) {
data = intial;
nextnode = null;
}
public int getData() {
return data;
}
public Node getNext() {
return nextnode;
}
public void setData(int newdata) {
data = newdata;
}
public void setNode(Node next1node) {
nextnode = next1node;
}
}
I tried:
public void push(Node n) {
Node next = n;
top.getNext().setNode(n);
}
Result:
Exception in thread "main" java.lang.NullPointerException
at javaclass.stack.pStack.push(pStack.java:24)
at javaclass.stack.StackDriver.main(StackDriver.java:17)
public void push(Node n) {
n.setNode(top);
top = n;
}
Edit:
BTW, this is an odd implementation of a stack. It looks like it wants to be a stack of int primitives. Both peek() and pop() return an int. But then push takes an argument that should be an internal construct of the stack itself. It shouldn't take a Node object as an argument. It should take an int argument and wrap it with the Node object internally.
Also, Node.setNode should be named Node.setNext. It's just more consistent with what you are doing. A linked list node has a "next" member and a double linked list node has "next" and "previous" members. The getters and setters of the node object should be appropriately named for those members.
Like this:
PStack.java
public class PStack {
private Node top;
public boolean isEmpty() {
return top==null;
}
public int pop() {
Node top1 = top;
top = top.getNext();
return top1.getData();
}
public void push(int data) {
Node newtop = new Node(data);
newtop.setNext(top);
top = newtop;
}
public int peek() {
return top.getData();
}
}
Node.java
public class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
}
public int getData() {
return data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
So I wrote my own linked list (and list node) in Java as a part of a homework.
Now, I'm trying to erase entries, but the function is not working.
I know the concept:
Search for node keeping the previous;
Tell previous node to point to next node;
Return or stop using the node so GC erases it.
For some reason it is not working. I can delete the node with the same value over and over. I'm afraid it is something related to Java pointers.
The code:
Node:
public class SimpleNode<E> {
private E value;
private SimpleNode<E> next;
public SimpleNode() {
this.value = null;
this.next = null;
}
public NoSimples(E data, SimpleNode<E> ref) {
this.value = data;
this.next = ref;
}
// Getters and Setters
}
List:
public class LinkedList<E> implements Iterable<SimpleNode<E>> {
private SimpleNode<E> head;
private int size = 0;
public LinkedList() {
this.head = new SimpleNode<E>();
}
public void add(SimpleNode<E> node) {
this.addFirst(node.getValue());
}
public void addFirst(E item) {
SimpleNode<E> nonde = new SimpleNode<E>(item, this.head);
this.head = node;
size++;
}
public void add(E value) {
this.addFirst(value);
}
public SimpleNode<E> removeFirst() {
SimpleNode<E> node = this.head;
if (node == null) {
return null;
} else {
this.head = node.getNext();
node.setNext(null);
this.size--;
return node;
}
}
public SimpleNodes<E> remove(E value) {
SimpleNode<E> nodeAnt = this.head;
SimpleNode<E> node = this.head.getNext();
while (node != null) {
if (node.getValue()!= null && node.getValue().equals(value)) {
nodeAnt.setNext(node.getNext());
node.setNext(null);
return node;
}
nodeAnt = node;
node = node.getNext();
}
return null;
}
// Other irrelevant methods.
}
Multiple Problems :
Think if you have a list 1,2,3,4. Now, if you try to remove 1, your code fails.
nodeAnt = node should be nodeAnt = nodeAnt.getNext(). Remember, the're all references, not Objects
Also, a recursive way might be easier to understand. For example, Here is how I implemented it
public void remove(E e){
prev = head;
removeElement(e, head);
System.gc();
}
private void removeElement(E e, Node currentElement) {
if(currentElement==null){
return;
}
if(head.getData().equals(e)){
head = head.getNext();
size--;
}else if(currentElement.getData().equals(e)){
prev.setNext(currentElement.getNext());
size--;
}
prev = prev.getNext();
removeElement(e, currentElement.getNext());
}
Note: I delete all occurrences of the Element, as I needed it. You may need it to be different.
I do not understand why printList() loops infinitely when called. I am attempting to code a stack linked list and print the list without using the built-in stack methods in java. Why is my print method looping infinitely and how do I correct this issue?
public class LinkedListStack{
private String item;
private Node next;
private Node top = null;
public LinkedListStack(){
}
public void push(String item){
top = new Node(item, top);
}
public void printList(){
Node currentNode = top;
for(currentNode = top; currentNode.getItem()!= null; currentNode = currentNode.getNext()){
System.out.println(currentNode.getItem());
}
}
public class Node{
public Node(String newItem, Node nextNode){
item = newItem;
next = nextNode;
}
public Node(String newItem){
item = newItem;
next = null;
}
//to set the value of the next field
public void setNext(Node nextNode){
next = nextNode;
}
//read the value of the next field
public Node getNext(){
return(next);
}
//to set the value of the item field
public String setItem(String newItem){
item = newItem;
return(item);
}
//read the value of the item field
public String getItem(){
return(item);
}
}
public static void main(String args[]){
LinkedListStack newList = new LinkedListStack();
newList.push("hello");
newList.push("goodbye");
newList.printList();
}
}
The problem is that item and next are fields of LinkedListStack and shared between all Node instances. When you create another Node and set the item you change all nodes. To fix it just move the field declarations to the Node inner class.
Beside that, your loop's condition in the printList method is wrong: the next node is null, not its item.
Here is a working example:
public class LinkedListStack {
private Node top = null;
public LinkedListStack() {
}
public void push(final String item) {
top = new Node(item, top);
}
public void printList() {
Node currentNode = top;
for (currentNode = top; currentNode != null; currentNode = currentNode.getNext()) {
System.out.println(currentNode.getItem());
}
}
public class Node {
private String item;
private Node next;
public Node(final String newItem, final Node nextNode) {
item = newItem;
next = nextNode;
}
public Node(final String newItem) {
item = newItem;
next = null;
}
// to set the value of the next field
public void setNext(final Node nextNode) {
next = nextNode;
}
// read the value of the next field
public Node getNext() {
return next;
}
// to set the value of the item field
public String setItem(final String newItem) {
item = newItem;
return item;
}
// read the value of the item field
public String getItem() {
return item;
}
}
public static void main(final String args[]) {
final LinkedListStack newList = new LinkedListStack();
newList.push("hello");
newList.push("goodbye");
newList.printList();
}
}
Hey ya'll I am having a little trouble with my singly linked list. I decided to create a simple one because we do not get enough practice during my data structures class and cannot seem to find why I am not getting the right output.
The code is:
package linked_list;
public class LinkedList {
private Node head;
private Node tail; // After figuring out head, come back to this FIXME
private int listSize;
public LinkedList() {
head = new Node(null);
tail = new Node(null);
}
public void addLast(String s) {
Node newNode = new Node(s);
if (head == null) {
addFirst(s);
} else {
while (head.next != null) {
head = head.next;
}
head.next = newNode;
tail = newNode;
}
listSize++;
}
public void addFirst(String s) {
Node newNode = new Node(s);
if (head == null) {
head = newNode;
tail = newNode;
}
else {
newNode.next = head;
head = newNode;
}
listSize++;
}
public Object getFirst() {
return head.data;
}
public Object getLast() {
return tail.data;
}
public void clear() {
head = null;
tail = null;
listSize = 0;
}
public Object peek() {
try {
if (head == null) {
throw new Exception ("The value is null");
}
else {
return head;
}
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
public int size() {
return listSize;
}
// This class has the ability to create the nodes that are used
// in the Linked List.
private class Node {
Node next;
Object data;
public Node(String value) {
next = null;
data = value;
}
public Node(Object value, Node nextValue) {
next = nextValue;
data = value;
}
public Object getData() {
return data;
}
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
}
Now here is my driver that I created to run a simple little operation:
package linked_list;
public class LinkedListDriver {
public static void main(String[] args) {
LinkedList list1 = new LinkedList();
list1.clear();
list1.addLast("This goes last");
list1.addFirst("This goes first");
list1.addLast("Now this one goes last");
System.out.println(list1.getFirst());
System.out.println(list1.getLast());
}
}
My output is this:
This goes last
Now this one goes last
I guess my question is why am I not getting the answer This goes first from my getFirst() method. It seems to be something wrong with the order or structure of that method but I cannot pinpoint it.
When you are in the else in the addLast, you are changing the reference to head. You should use another reference pointer to traverse the list when adding in the else.
Also, your list size should only be incremented in the else in addLast because you are incrementing twice otherwise (once in addFirst and again after the if-else in addLast).
I have been diligently watching YouTube videos in an effort to understand linked lists before my fall classes start and I am uncertain how to proceed with iterating over the following linked list. The 'node' class is from a series of videos (same author), but the 'main' method was written by me. Am I approaching the design of a linked list in an illogical fashion (assuming of course one does not wish to use the predefined LinkedList class since the professor will expect each of us to write our own implementation)?:
class Node
{
private String data;
private Node next;
public Node(String data, Node next)
{
this.data = data;
this.next = next;
}
public String getData()
{
return data;
}
public Node getNext()
{
return next;
}
public void setData(String d)
{
data = d;
}
public void setNext(Node n)
{
next = n;
}
public static String getThird(Node list)
{
return list.getNext().getNext().getData();
}
public static void insertSecond(Node list, String s)
{
Node temp = new Node(s, list.getNext());
list.setNext(temp);
}
public static int size(Node list)
{
int count = 0;
while (list != null)
{
count++;
list = list.getNext();
}
return count;
}
}
public class LL2
{
public static void main(String[] args)
{
Node n4 = new Node("Tom", null);
Node n3 = new Node("Caitlin", n4);
Node n2 = new Node("Bob", n3);
Node n1 = new Node("Janet", n2);
}
}
Thanks for the help,
Caitlin
There are some flaws in your linked list as stated by some of the other comments. But you got a good start there that grasps the idea of a linked list and looks functional. To answer your base question of how to loop over this particular implemention of the linked list you do this
Node currentNode = n1; // start at your first node
while(currentNode != null) {
// do logic, for now lets print the value of the node
System.out.println(currentNode.getData());
// proceed to get the next node in the chain and continue on our loop
currentNode = currentNode.getNext();
}
Maybe this will be useful:
static void iterate(Node head) {
Node current = head;
while (current != null) {
System.out.println(current.getData());
current = current.getNext();
}
}
// or through recursion
static void iterateRecursive(Node head) {
if (head != null) {
System.out.println(head.getData());
iterateRecursive(head.getNext());
}
}
class List {
Item head;
class Item {
String value; Item next;
Item ( String s ) { value = s; next = head; head = this; }
}
void print () {
for( Item cursor = head; cursor != null; cursor = cursor.next )
System.out.println ( cursor.value );
}
List () {
Item one = new Item ( "one" );
Item two = new Item ( "three" );
Item three = new Item ( "Two" );
Item four = new Item ( "four" );
}
}
public class HomeWork {
public static void main( String[] none ) { new List().print(); }
}
Good luck!!
You can have your linked list DS class implement 'Iterable' interface and override hasNext(), next() methods or create an inner class to do it for you. Take a look at below implementation:
public class SinglyLinkedList<T>{
private Node<T> head;
public SinglyLinkedList(){
head = null;
}
public void addFirst(T item){
head = new Node<T>(item, head);
}
public void addLast(T item){
if(head == null){
addFirst(item);
}
else{
Node<T> temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = new Node<T>(item, null);
}
}
private static class Node<T>{
private T data;
private Node<T> next;
public Node(T data, Node<T> next){
this.data = data;
this.next = next;
}
}
private class LinkedListIterator implements Iterator<T>{
private Node<T> nextNode;
public LinkedListIterator(){
nextNode = head;
}
#Override
public boolean hasNext() {
return (nextNode.next != null);
}
#Override
public T next() {
if(!hasNext()) throw new NoSuchElementException();
T result = nextNode.data;
nextNode = nextNode.next;
return result;
}
}
}