I must create Stack by using Linked List. Here is my LinkedList class:
package stack;
import java.util.EmptyStackException;
public class List {
Element head;
int size = 0;
public void Add(Object value) {
if (size == 0) {
head = new Element(value);
size++;
return;
}
Insert(size, value);
}
public void Insert(int index, Object value) {
if (index > size) {
throw new IndexOutOfBoundsException("Bad index");
}
Element tmp = head;
for (int i = 0; i < index -1 ; i++) {
tmp = tmp.next;
}
Element newElement = new Element(value);
newElement.next = tmp.next;
tmp.next = newElement;
size++;
}
public int Size() {
return size;
}
public Object Get(int index) {
if (index > size - 1) {
throw new IndexOutOfBoundsException("Index doesn't exist");
}
Element tmp = head;
for (int i = 0; i < index; i++) {
tmp = tmp.next;
}
System.out.println(tmp.value.toString());
return tmp;
}
public Object Set(int index, Object value) {
if (index > size - 1) {
throw new IndexOutOfBoundsException("Index doesn't exist");
}
Element tmp = head;
for (int i = 0; i < index; i++) {
tmp = tmp.next;
}
Element returnValue = new Element(value);
returnValue = tmp;
tmp.value = value;
return returnValue;
}
public Object Delete(int index) {
Element tmp;
tmp = head;
for (int i = 0; i < index - 1; i++) {
tmp = tmp.next;
}
Element returnValue;
returnValue = tmp;
head = tmp.next;
size--;
return returnValue;
}
public boolean Contains(Object value) {
Element tmp = head;
for (int i = 0; i < size - 1; i++) {
tmp = tmp.next;
if (tmp.value == value) {
System.out.println("true");
return true;
}
}
System.out.println("False");
return false;
}
public boolean IsEmpty() {
return Size() > 0;
}
public void Clear() {
size = 0;
}
public void Display() throws EmptyStackException {
if (size <= 0) {
throw new EmptyStackException();
}
Element tmp = head;
for (int i = 0; i < size; i++) {
System.out.println(tmp.value.toString());
tmp = tmp.next;
}
}
}
and i got Stack interface
public interface IStack {
public interface Stack {
public void push(Object value); // odłóż na stos
public Object pop() throws EmptyStackException; //pobierz ze stosu
public Object peek() throws EmptyStackException; //odczytaj ze stosu,
// and some others
Any1 have am idea how to create pop method?
LinkedList is already a stack, it has pop, push and peek methods. Just create an adapter class and use those methods
Related
So I'm doing a Java dynamic queue with implemented array, and when the array are doubling in size, and the values from the previous array have been copied over, and additional values added, the program returns null on the first additional value.
It is supposed to return 10.
Console returns following:
...
9
Queue is full. Allocating bigger array.
Queue length is now doubled, and nodes copied
10
...
14
Start dequeue.
0
...
9
null
11
...
Main class:
public class Main{
public static void main(String[] args) throws Exception{
int maxsize = 10;
Array queue = new Array(maxsize);
for(int i=0; i<15; i++) {
queue.enQueue(i);
}
System.out.println("Start dequeue.");
for(int i=0; i<15; i++) {
System.out.println(queue.deQueue());
}
}
}
Array Class:
public class Array {
private Node[] queue;
private Integer head; // index of the current front item, if one exists
private Integer tail; // index of next item to be added
private int maxSize;
private int size = 0;
public Array(int maxSize) {
this.maxSize = maxSize;
queue = new Node[maxSize+1];
for(int i = 0; i <= maxSize; i++) {
queue[i] = new Node(null);
}
head = tail = 0;
}
public void enQueue(Integer data){
Node node = new Node(data);
// If it's the first node, put in queue[0], increase tail.
if(head == tail && size == 0) {
queue[tail] = node;
tail++;
size++;
System.out.println(data);
// If Queue is full, create array twice the size and copy elements.
}else if(size == maxSize) {
System.out.println("Queue is full. Allocating bigger array.");
int newMaxSize = maxSize * 2;
// Skapa och initialisera ny Array.
Node[] newQueue = new Node[newMaxSize + 1];
for(int i = 0; i <= newMaxSize; i++) {
newQueue[i] = new Node(null);
}
// Kopiera över element mellan head -> maxSize.
for(int i = head; i <= maxSize; i++) {
int j = 0;
newQueue[j] = queue[i];
j++;
}
// Kopiera över element mellan queue[0] -> tail.
for(int i=0; i<=tail; i++) {
if(queue[i] != null) {
newQueue[i] = queue[i];
}
}
tail = maxSize + 1;
maxSize = newMaxSize;
queue = newQueue;
head = 0;
queue[tail] = node;
size++;
System.out.println("Queue length is now doubled, and nodes copied");
System.out.println(data);
return;
// If Queue is not full, check if tail point outside of maxSize.
}else {
// If tail is outside, move tail to queue[0].
if(tail == maxSize + 1) {
tail = 0;
queue[tail] = node;
tail++;
size++;
}else {
queue[tail] = node;
tail++;
size++;
}
System.out.println(data);
}
}
public Integer deQueue() {
if(head != tail) {
if(head == maxSize) {
Integer nodeData = queue[head].getData();
queue[head] = null;
head = 0;
size--;
return nodeData;
} else {
Integer nodeData = queue[head].getData();
queue[head] = null;
head++;
size--;
return nodeData;
}
} else {
// If queue is empty, notify user.
System.out.println("Queue is empty.");
return null;
}
}
}
Node class:
public class Node {
private Integer data;
public Node(Integer data) {
this.data = data;
}
public Integer getData() {
return this.data;
}
}
I'm stuck by staring at the code for too long, not able to find the issue.
Help would be appreciated!
public class ourStack1 {
private int elements[];
private int index; // indicate the next position to put a new data
private int size;
public ourStack1() {
elements = new int[10];
index = 0;
size = 0;
}
public void push(int value) {
if(size == 10) {
System.out.println("Stack is full, no push");
return;
}
elements[index] = value;
++index;
++size;
}
public int pop() {
if(size == 0) {
System.out.println("Stack is empty, no pop");
return -1;
}
int temp = elements[index - 1];
--index;
--size;
return temp;
}
public int peek() {
if(size == 0) {
System.out.println("Stack is empty, no peek");
return -1;
}
return elements[index - 1];
}
/*
public int mySize() {
// you know how to do this
}
*/
public static void main(String[] args) {
ourStack1 x = new ourStack1();
for(int i = 0; i < 10; ++i)
x.push(i);
for(int i = 0; i < 10; ++i)
System.out.println(x.pop());
}
}
I'm confused on how to overwrite the last element added to the full stack. I want to add element to replace the last element while not exceeding the array size[10]
public void replaceLast(int value) {
if (this.size > 0) {
this.pop();
}
this.push(value);
}
I am trying to implement a CircularArrayQueue. I've been given a JUnit test which my queue must pass.I suppose I am doing something wrong with the front and rear pointers. How should i approach learning data structures and algorithms ?
import java.util.NoSuchElementException;
public class CircularArrayQueue implements MyQueue {
private Integer[] array;
// initial size of the array
private int N;
private int front;
private int rear;
public CircularArrayQueue() {
this.N = 10;
array = new Integer[N];
front = rear = 0;
}
public CircularArrayQueue(int size) {
this.N = size;
array = new Integer[N];
front = rear = 0;
}
// enqueues an element at the rear of the queue
// if the queue is already full it is resized, doubling its size
#Override
public void enqueue(int in) {
if (rear == N) {
if (front == 0) {
resize();
array[rear] = in;
rear++;
} else {
array[rear] = in;
rear = 0;
}
} else {
array[rear] = in;
rear++;
}
}
public void resize() {
Integer[] temp = new Integer[array.length * 2];
for (int i = 0; i < array.length; i++) {
temp[i] = array[i];
}
temp = array;
}
// dequeues an element
// if the queue is empty a NoSuchElement Exception is thrown
#Override
public int dequeue() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The queue is full");
}
int headElement = array[front];
if (front == N) {
array[front] = null;
front = 0;
} else {
array[front] = null;
front++;
}
return headElement;
}
#Override
public int noItems() {
return N - getCapacityLeft();
}
#Override
public boolean isEmpty() {
return (getCapacityLeft() == N);
}
// return the number of indexes that are empty
public int getCapacityLeft() {
return (N - rear + front) % N;
}
}
Your initialization is absolutely fine, and we do start with:
front = rear = 0;
Befor adding an item to the Q, we modify rear as
rear = (rear + 1) % N;
The % allows us to maintain the circular property of the queue. Also you must be wondering that if we modify rear before adding any item, then 0 index is left empty, well we have to compromise here with one array item being left blank, in order to have correct implementations for checking of isEmpty() and isFull() functions:
That said, the correct code for isEmpty() is:
#Override
public boolean isEmpty()
{
return front == rear;
}
You should also have a function isFull() like:
#Override
public boolean isFull()
{
return front == ((rear + 1) % N);
}
Also the line temp = array; in your resize() should be array = temp; and you must also update the value of N after calling resize().
Hence, the correct code is:
import java.util.NoSuchElementException;
public class CircularArrayQueue implements MyQueue
{
private Integer[] array;
//initial size of the array
private int N;
private int front;
private int rear;
private int count = 0;//total number of items currently in queue.
public CircularArrayQueue()
{
this.N = 10;
array = new Integer[N];
front = rear = 0;
}
public CircularArrayQueue(int size)
{
this.N = size;
array = new Integer[N];
front = rear = 0;
}
//enqueues an element at the rear of the queue
// if the queue is already full it is resized, doubling its size
#Override
public void enqueue(int in)
{
count++;
if (isFull())
{
resize();
rear = (rear + 1) % N;
array[rear] = in;
}
else
{
rear = (rear + 1) % N;
array[rear] = in;
}
}
public void resize()
{
Integer[] temp = new Integer[array.length*2];
N = array.length*2;
for(int i=0; i<array.length; i++)
{
temp[i] = array[i];
}
array = temp;
}
//dequeues an element
// if the queue is empty a NoSuchElement Exception is thrown
#Override
public int dequeue() throws NoSuchElementException
{
if(isEmpty())
{
throw new Exception("The queue is empty");
}
front = (front + 1) % N;
int headElement = array[front];
count--;
return headElement;
}
#Override
public int noItems()
{
return count;
}
#Override
public boolean isEmpty()
{
return front == rear;
}
#Override
public boolean isFull()
{
return front == ((rear + 1) % N);
}
//return the number of indexes that are empty
public int getCapacityLeft()
{
return N - 1 - count;
}
}
On my count method, i am trying to compare the object being sent with the object calling it, and I have no idea why i can not cal o.get(i) to get the value for Object o being passed. It tells me the method cannot be found even though i can call get(i) normally. Any ideas how i can get the value for the object getting passed so i can compare them?
public class GenericLinkedList<E> implements List<E> {
private class Node<E>{
private E data;
private Node<E> next;
}
private E data;
private Node<E> head = null;
private int size = 0;
private Node<E> nodeAt(int index){
Node<E> curNode = head;
int curIndex = 0;
while(curIndex < index){
curNode = curNode.next;
curIndex++;
}
return curNode;
}
#Override
public E get(int index) {
return nodeAt(index).data;
}
#Override
public void add(E value) {
Node<E> node = new Node<E>();
node.data = value;
if(size == 0){
head = node;
}else{
Node<E> curNode = nodeAt(size - 1);
curNode.next = node;
}
size++;
}
public void add(int index, E value){
Node<E> node = new Node<E>();
node.data = value;
if(size == 0){
head = node;
}else if(index == 0){
node.next = head;
head = node;
}else{
Node<E> curNode = nodeAt(index - 1);
node.next = curNode.next;
curNode.next = node;
}
size++;
}
#Override
public void remove(int index) {
if(index == 0){
head = head.next;
}else{
Node<E> curNode = nodeAt(index - 1);
curNode.next = curNode.next.next;
}
size--;
}
#Override
public void set(int index, E value) {
nodeAt(index).data = value;
}
public String toString(){
String s = "";
Node<E> curNode = head;
s += curNode.data +" -> ";
while(curNode.next != null){
curNode = curNode.next;
s += curNode.data +" -> ";
}
s += "null";
return s;
}
public void clear() {
for (int i = 0; i < size; i++)
set(i, null);
size = 0;
}
#Override
public void removeAll(E o)//Clears out the array object by setting everything to null
{
for(int i = 0; i < this.size; i++)
{
}
}
#Override
public int count(Object o)
{
System.out.println(o);
int count = 0;
for(int i = 0; i< size;i++)
{
if(get(i) == o.get(i))
{
count++;
}
}
return count;
/*int count = 0;
for(int i = 0;i<this.size;i++)
{
for(int j = 0;i<size;j++)
{
}
}
return count;*/
}
public void reverse()
{
int x = size;
for(int i = 0; i < this.size; i++)
{
E temp = this.get(x);
this.set(x, get(i));
this.set(i, temp);
x++;
}
}
public Object subList(int beginIndex, int endIndex)
{
int j = 0;
GenericLinkedList<E> LinkedList = new GenericLinkedList<E>();
if(beginIndex == endIndex)
return LinkedList;
else if(beginIndex > endIndex||endIndex>size||beginIndex<0)
{
return null;
}
else
{
for(int i = beginIndex; i <= endIndex;i++)
{
LinkedList.add(get(i));
j++;
}
}
return LinkedList;
}
public static void main(String[] args) {
GenericLinkedList<Integer> myList = new GenericLinkedList<Integer>();
myList.add(4);
myList.add(7);
myList.add(123123);
System.out.println(myList.get(2));
GenericLinkedList<Integer> myList2 = new GenericLinkedList<Integer>();
myList2.add(4);
myList2.add(7);
myList2.add(8);
myList2.add(3,999);
System.out.println(myList2);
System.out.println(myList.count(myList2));
//System.out.println(myList2);
// myList2.clear();//Testing our clear class
// System.out.println(myList2);
//System.out.println(myList2.subList(1, 3));//Testing our clear class
// System.out.println(myList2);
}
}
You have a problem when trying to call o.get() because it is an object of the base type Object which has no method get defined. To get the proper result you have two possible solutions....
The short solution is to type cast.
((GenericLinkedList<Object>)o).get(i)
Or a more easily readable solution is to change the signature of your count method:
public int count(GenericLinkList<E> list) {
...
}
Change your count method to public int GenericLinkedList(Object o)
If you use Object as the type of the parameter, you can only call the methods which are available on Object.
I'm writing this code to implement a stack as a linked list but I keep getting an error when I compile this part of the code and can't figure out why
I definitely know that it shouldn't be giving me this error since there are enough brackets and none of them are out of place I hope
The Error:
C:\Users\Michelle\Desktop\ITB\Semester 5\Data Structures & Algorithms\Assignment\ListReference.java:108: error: reached end of file while parsing
}
^
1 error
My Code:
public class ListReference implements StackInterface {
private Node top;
//private Object item;
private int NumItems;
public ListReference() {
NumItems = 0;
top = new Node(null);
}
public boolean isEmpty() {
return NumItems == 0;
}
public int size() {
return NumItems;
}
/*public Node find(int index) {
Node curr = tail;
for(int skip = 1; skip < index; skip++) {
curr.getNext();
}
return curr;
}*/
public Object get(int index) {
if(index <= 0)
return null;
Node ListReference = top.getNext();
for(int i=1; i < index; i++) {
if (ListReference.getNext() == null)
return null;
ListReference = ListReference.getData();
}
}
public void add(int index, Object item) {
Node ListReferenceTemp = new Node(item);
Node ListRefCurr = top;
while(ListRefCurr.getNext() != null) {
ListRefCurr = ListRefCurr.getNext();
}
ListRefCurr.setNext(ListReferenceTemp);
NumItems++;
}
public void add(Object data) {
Node ListReferenceTemp = new Node(item);
Node ListRefernce = top;
for(int i=1; i < index && ListReference.getNext() != null; i++) {
ListReference = ListReference.getNext();
}
ListReferenceTemp.setNext(ListReference.getNext());
ListReference.setNext(ListReferenceTemp);
NumItems++;
}
// removes the element at the specified position in this list.
public boolean remove(int index) {
// if the index is out of range, exit
if (index < 1 || index > size())
return false;
Node ListRefCurr = top;
for (int i = 1; i < index; i++) {
if (ListRefCurr.getNext() == null) {
return false;
}
ListRefCurr = ListRefCurr.getNext();
}
ListRefCurr.setNext(ListRefCurr.getNext().getNext());
NumItems--; // decrement the number of elements variable
return true;
}
public String toString() {
Node ListReference = top.getNext();
String output = "";
while (ListREference != null) {
output += "[" + ListRefCurr.getData().toString() + "]";
ListRefCurr = ListRefCurr.getNext();
}
return output;
}