程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java版本和C++版本簡單Stack程序

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

編輯:關於JAVA
現在對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;
  }
  }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved