簡體   English   中英

從 C++ 堆棧 class 創建 java generics 堆棧 class

[英]creating java generics stack class from C++ stack class

#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++ 代碼,用於可變數據類型的堆棧 class。 它執行基本的 function 彈出、推送。 我想將此代碼轉換為 java generics。因為我不太熟悉 java generics。請幫助我


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());

}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM