现在对c++学习了一段时间,把c++的特性和java做比较有很强烈的快感:p
自己写了两个版本的stack:
java版本:
源代码stack.java
package org;
public class stack ...{
public static class link ...{
protected object data;
protected link next;
public link(object data, link next) ...{
this.data = data;
this.next = next;
}
}
private link head = null;
public void push(object data) ...{
head = new link(data, head);
}
public object peek() ...{
return head.data;
}
public object pop() ...{
if (head == null)
return null;
object o = head.data;
head = head.next;
return o;
}
} 测试代码stacktest.java
package org;
import junit.framework.testcase;
public class stacktest extends testcase ...{
public void test1() ...{
stack s = new stack();
assertequals(null, s.pop());
s.push("a");
s.push("b");
assertequals("b", s.peek());
assertequals("b", s.pop());
assertequals("a", s.pop());
assertequals(null, s.pop());
}
public void test2() ...{
stack s = new stack();
assertequals(null, s.pop());
s.push(new integer(1));
s.push(new integer(2));
assertequals(2, ((integer)s.peek()).intvalue());
assertequals(2, ((integer)s.pop()).intvalue());
assertequals(1, ((integer)s.pop()).intvalue());
assertequals(null, s.pop());
}
}
c++版本:
源代码:
stack.cpp
#include
#include
#include
using namespace std;
class stack ...{
struct link ...{
link* next;
void* data;
link(void* dat, link* nxt) : data(dat) ,next(nxt) ...{}
}*head;
public :
stack() : head(0) ...{}
void push(void* data) ...{
head = new link(data, head);
}
void* pop() ...{
if (head == 0)
return 0;
void* object = head->data;
link* oldhead = head;
head = oldhead->next;
delete oldhead;
return object;
}
void* peek() ...{
return head ? head->data : 0;
}
};
int main() ...{
ifstream in("stack.cpp");
stack text;
string line;
while(getline(in, line))
text.push(new string(line));
string* s;
while((s = (string*)text.pop()) != 0) ...{
cout << *s << endl;
delete s;
}
}
闽公网安备 35060202000074号