#include <cstdlib>
#include<iostream>
using namespace std;
template <typename T>
class stack
{
public:
T arr[100];
int top;
stack()
{
top=-1;
}
public:
void push(T x)
{
if(top==99)
cout<<"overflow";
else
arr[++top]=x;
}
public :
T pop(void)
{
if(top==-1)
return 0;
else
return arr[top--];
}
};
int main(int argc, char** argv)
{
stack <int> s;
int x;
cout<<"\nEnter no : ";
cin>>x;
s.push(x);
x=s.pop();
cout<<"Element popped : "<<x;
return 0;
}
这是我的C ++代码,用于可变数据类型的堆栈类。它具有pop,push的基本功能。我想将此代码转换为java泛型。因为我不太熟悉java泛型。请帮帮我
答案 0 :(得分:0)
import java.util.EmptyStackException;
import java.util.Vector;
public class Stack extends Vector{
/**
* Creates an empty Stack.
*/
public Stack() {
}
public E pop() {
E obj;
int len = size();
if (len == 0)
throw new EmptyStackException();
obj = elementAt(len - 1);
removeElementAt(len - 1);
return obj;
}
public void push(E e) {
if(e==null)
throw new NullPointerException();
addElement(e);
}
public int size() {
return elementCount;
}
public static void main(String args[]){
Stack<Integer> integerStack= new Stack<Integer>();
//(7,1,3,3,5,1,2,4,3)
integerStack.push(7);
integerStack.push(1);
integerStack.push(3);
integerStack.push(3);
integerStack.push(5);
integerStack.push(1);
integerStack.push(2);
integerStack.push(4);
integerStack.push(3);
System.out.println("STACK WITH INTEGER ELEMENTS");
//Size
System.out.println("Size of the Stack is : "+integerStack.size());
// String Stack
Stack<String> stringStack= new Stack<String>();
//("abc","def","acd","fgi","fth","lmn","zxy","cde","adr")
stringStack.push("abc");
stringStack.push("def");
stringStack.push("acd");
stringStack.push("fgi");
stringStack.push("fth");
stringStack.push("lmn");
stringStack.push("zxy");
stringStack.push("cde");
stringStack.push("adr");
System.out.println("STACK WITH STRING ELEMENTS");
//Size
System.out.println("Size of the Stack is : "+stringStack.size());
//pop
stringStack.pop();
//Size after pop
System.out.println("Size of the Stack After pop is : "+stringStack.size());
}
}