Hi people. Nice to meet you. I'm trying to do the following assignment from Robert Sedgewick's book:
However, I have no idea how to implement this because I'm using references in a linked list not arrays.
I coded this:
Quote
Write a method delete() that takes an int argument k and deletes the kth ele-
ment in a linked list, if it exists.
ment in a linked list, if it exists.
However, I have no idea how to implement this because I'm using references in a linked list not arrays.
I coded this:
package stack;
public class LinkedListStack<Item> {
private Node first;
private int N;
private class Node
{
Item item;
Node next;
}
public boolean isEmpty()
{
return first == null;
}
public int size()
{
return N;
}
public void delete(int k)
{
throw new UnsupportedOperationException();
}
public void push(Item item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
N++;
}
public void peek()
{
System.out.println("Last node contains: " + first.item);
}
public Item pop()
{
Item item = first.item;
first = first.next;
N--;
return item;
}
}
package stack;
public class LinkedListStackTest {
public static void main(String[] args) {
LinkedListStack<String> lls = new LinkedListStack();
lls.push("a");
lls.push("b");
lls.push("c");
lls.push("d");
lls.peek();
}
}