熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

Java版本和C++版本簡單Stack程序

2022-06-13   來源: .NET編程 

  現在對C++學習了一段時間把C++的特性和Java做比較有很強烈的快感:P

自己寫了兩個版本的Stack:

Java版本:

源代碼Stackjava
package org;
public class Stack {
public static class Link {

protected Object data;

protected Link next;

public Link(Object data Link next) {
thisdata = data;
thisnext = next;
}
}

private Link head = null;

public void push(Object data) {
head = new Link(data head);
}

public Object peek() {
return headdata;
}

public Object pop() {
if (head == null)
return null;
Object o = headdata;
head = headnext;
return o;
}

} 測試代碼StackTestjava
package org;
import junitframeworkTestCase;

  public class StackTest extends TestCase {

public void test() {
Stack s = new Stack();

assertEquals(null spop());

spush(a);
spush(b);

assertEquals(b speek());
assertEquals(b spop());
assertEquals(a spop());

assertEquals(null spop());
}

public void test() {
Stack s = new Stack();

assertEquals(null spop());

spush(new Integer());
spush(new Integer());

assertEquals( ((Integer)speek())intValue());
assertEquals( ((Integer)spop())intValue());
assertEquals( ((Integer)spop())intValue());

assertEquals(null spop());
}

}

C++版本:
源代碼:
Stackcpp
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

  class Stack {
struct Link {
Link* next;
void* data;
Link(void* dat Link* nxt) : data(dat) next(nxt) {}
}*head;

public :
Stack() : head() {}

void push(void* data) {
head = new Link(data head);
}

void* pop() {
if (head == )
return ;
void* object = head>data;
Link* oldHead = head;
head = oldHead>next;
delete oldHead;
return object;
}

void* peek() {
return head ? head>data : ;
}
};

int main() {
ifstream in(Stackcpp);
Stack text;
string line;
while(getline(in line))
textpush(new string(line));
string* s;
while((s = (string*)textpop()) != ) {
cout << *s << endl;
delete s;
}
}


From:http://tw.wingwit.com/Article/program/net/201311/11550.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.