现在对C++学习了一段时间,把C++的特性和Java做比较有很强烈的快感:P
自己写了两个版本的Stack:
Java版本:
源代码Stack.java
packageorg;

publicclassStack...{

publicstaticclassLink...{

protectedObjectdata;

protectedLinknext;


publicLink(Objectdata,Linknext)...{
this.data=data;
this.next=next;
}
}

privateLinkhead=null;


publicvoidpush(Objectdata)...{
head=newLink(data,head);
}


publicObjectpeek()...{
returnhead.data;
}


publicObjectpop()...{
if(head==null)
returnnull;
Objecto=head.data;
head=head.next;
returno;
}

}
测试代码StackTest.java
packageorg;
importjunit.framework.TestCase;


publicclassStackTestextendsTestCase...{


publicvoidtest1()...{
Stacks=newStack();

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


publicvoidtest2()...{
Stacks=newStack();

assertEquals(null,s.pop());

s.push(newInteger(1));
s.push(newInteger(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<fstream>
#include<iostream>
#include<string>
usingnamespacestd;


classStack...{

structLink...{
Link*next;
void*data;

Link(void*dat,Link*nxt):data(dat),next(nxt)...{}
}*head;

public:

Stack():head(0)...{}


voidpush(void*data)...{
head=newLink(data,head);
}


void*pop()...{
if(head==0)
return0;
void*object=head->data;
Link*oldHead=head;
head=oldHead->next;
deleteoldHead;
returnobject;
}


void*peek()...{
returnhead?head->data:0;
}
};


intmain()...{
ifstreamin("Stack.cpp");
Stacktext;
stringline;
while(getline(in,line))
text.push(newstring(line));
string*s;

while((s=(string*)text.pop())!=0)...{
cout<<*s<<endl;
deletes;
}
}
自己写了两个版本的Stack:
Java版本:
源代码Stack.java















































































C++版本:
源代码:
Stack.cpp






















































