扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
现在对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 <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(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;
}
}
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者