题目描述

已知链栈类的定义、构造函数及main函数如下,请完成其余的成员函数实现。
template
class LinkStack
{
public:
LinkStack( ); //构造函数,置空链栈
~LinkStack( ); //析构函数,释放链栈中各结点的存储空间
void Push(T x); //将元素x入栈
T Pop( ); //将栈顶元素出栈
T GetTop( ); //取栈顶元素(并不删除)
bool Empty( ); //判断链栈是否为空栈
private:
Node top; //栈顶指针即链栈的头指针
};

/

前置条件:栈不存在
输 入:无
功 能:栈的初始化
输 出:无
后置条件:构造一个空栈
/

template
LinkStack::LinkStack( )
{
top=NULL;
}
int main()
{
LinkStack s;
char ch;
while(1)
{
cin>>ch;
if(ch==’#’) break;
s.Push(ch);
}
cout<<”Gettop:”< while(!s.Empty())
{
cout< }
cout< try{
cout<<”Gettop:”< }
catch(const char *ms){
cout<<”Gettop:”< }
return 0;
}

输入

输出

样例输入

asdfgh#

样例输出

Gettop:h
h g f d s a
Gettop:Downflow

提示

来源

提交

  1. import java.util.Scanner;
  2. class Node {
  3. public Object data;
  4. public Node next;
  5. public Node() {
  6. this(null,null);
  7. }
  8. public Node(Object data) {
  9. this(data,null);
  10. }
  11. public Node(Object data, Node next) {
  12. this.data = data;
  13. this.next = next;
  14. }
  15. }
  16. class LinkStack{
  17. Node top;
  18. public LinkStack() {
  19. top = null;
  20. }
  21. public void push(Object x){
  22. top = new Node(x,top);
  23. }
  24. public Object pop() throws Exception {
  25. if(isEmpty()){
  26. throw new Exception("Downflow");
  27. }else {
  28. Node p = top;
  29. top = top.next;
  30. return p.data;
  31. }
  32. }
  33. public Object getTop() throws Exception {
  34. if(isEmpty()){
  35. throw new Exception("Downflow");
  36. }else {
  37. return top.data;
  38. }
  39. }
  40. public boolean isEmpty(){
  41. return top==null;
  42. }
  43. }
  44. public class Main {
  45. public static void main(String[] args) {
  46. LinkStack l = new LinkStack();
  47. Scanner sc = new Scanner(System.in);
  48. String s = sc.next();
  49. for (int i = 0; i < s.length(); i++) {
  50. if(s.charAt(i) == '#')break;
  51. l.push(s.charAt(i));
  52. }
  53. try{
  54. System.out.println("Gettop:"+l.getTop());
  55. } catch (Exception e) {
  56. System.out.println("Gettop:"+e.getMessage());
  57. }
  58. while (!l.isEmpty()){
  59. try {
  60. System.out.print(l.pop() + " ");
  61. } catch (Exception e) {
  62. System.out.println("Pop:"+e.getMessage());
  63. }
  64. }
  65. System.out.println();
  66. try{
  67. System.out.println("Gettop:"+l.getTop());
  68. } catch (Exception e) {
  69. System.out.println("Gettop:"+e.getMessage());
  70. }
  71. }
  72. }