Reputation: 163
Just finished spring break, having a hard time remembering some of this stuff.
Right now i am trying to create a Lstack class that will create a stack ADT implemented as a linked list of Nodes.
This is the Lstack class
public class Lstack {
int numUsed = 0;
Lstack list = new Lstack();
public Lstack(){
}
public void push(Car x){
}
}
How do i go about pushing Car x (an object) into the stack?
Upvotes: 0
Views: 146
Reputation: 163
Did i do this right?
public class Lstack {
int size;
int numUsed = 0;
Car[] list;
public Lstack(){
list = new Car[size];
}
public void push(Car x){
list[numUsed] = x;
numUsed++;
}
public Car pop(){
Car temp;
numUsed--;
temp = list[numUsed];
return temp;
}
public boolean isEmpty(){
if(numUsed==0){
return true;
}
else
return false;
}
public int size(){
return numUsed;
}
public void display(){
System.out.println("--------------------------------------------");
System.out.print("TOP | ");
for(int i = 0; i < numUsed; i++){
System.out.print(list[i].plate +" | ");
}
}
}
Upvotes: 0
Reputation: 21047
A stack is a Last-In / First-Out (LIFO) structure. So I would go this way:
The Car
class must have a next
member of the same class:
class Car {
String brand;
Car next;
public Car(String brand, Car car) {
this.brand = brand;
next = car;
}
// And the class code goes on
}
As for the linked list:
class Llist {
Car top;
public Llist() {
top = null;
}
public void push(String carBrand) {
top = new Car(carBrand, top);
}
}
Just an example.
Upvotes: 0
Reputation: 54074
A stack is a LIFO
structure.
So if you implement it backed by a linked list
then you should make sure that you push
into the same side of the list
that you pop
.
Since this is a homework I will not provide more info. This should be adequate
Upvotes: 5