創作內容

0 GP

【心得】stack使用linkedlist實作

作者:月不升│2018-10-18 19:38:41│巴幣:0│人氣:414
方便以後使用以及擴充功能 將此程式紀錄在這


struct CH {
  char ch;
  int num;
  CH *next;
};

class stack
{
  public:
  stack();
  ~stack();
  void push(char ch); //放入最上層
  void push(int num);
  void pop(); // 移除最上層
  char top(); // 取得最上層
  int num_top();
  void print(); // 印出stack
  bool isEmpty();
  void clear(); // 將stack裡的所有資料清空 釋放記憶體
  private:
  CH *ch_head;
  CH *ch_cur;
  int first;
};

stack::stack()
{
  first = 0;
}

stack::~stack()
{
}

bool stack::isEmpty() {
  if (first == 0)
    return true;
  else
    return false;
}

void stack::clear() {
  while (!isEmpty()) {
    pop();
  }
}

void stack::push(char ch) {

  if (first == 0) {
    ch_head = new CH;
    ch_cur = ch_head;
    ch_cur->ch = ch;
    ch_cur->next = NULL;
    first++;
  }
  else {

  CH *newPtr = new CH;
  ch_cur->next = newPtr;
  ch_cur = newPtr;
  ch_cur->ch = ch;
  ch_cur->next = NULL;

  }
}

void stack::push(int num) {
  if (first == 0) {
    ch_head = new CH;
    ch_cur = ch_head;
    ch_cur->num = num;
    ch_cur->next = NULL;
    first++;
  }
  else {
    CH *newPtr = new CH;
    ch_cur->next = newPtr;
    ch_cur = newPtr;
    ch_cur->num = num;
    ch_cur->next = NULL;
  }
}

void stack::pop() {

  if (!isEmpty()) {
    if (ch_head == ch_cur) {
    first = 0;
    delete ch_head;
  }
  else {
    CH *pre = new CH;
    CH *temp;
    CH *temp2;
    temp2 = pre;
    temp = ch_head;

    while (temp != NULL && temp != ch_cur) {
      if (temp->next == ch_cur)
        pre = temp;
        temp = temp->next;
      }

    temp = ch_cur;
    delete temp;
    ch_cur = pre;
    ch_cur->next = NULL;
    delete temp2;

    }
  }
}

char stack::top() {

  if( isEmpty()){
    return '\0';
  }
  else{

    if (ch_head->next == NULL) {
      return ch_head->ch;
    }
    else {
      return ch_cur->ch;
    }
  }

  return '\0';
}

int stack::num_top() {

  if (!isEmpty()) {
    if (ch_head->next == NULL) {
      return ch_head->num;
  }
  else {
    return ch_cur->num;
  }
}

  return 0;
}

void stack::print() {
  if (!isEmpty()) {
    CH *temp = new CH;
    temp = ch_head;
    cout << endl;
    while (temp != NULL) {
      cout << temp->ch << ",";
      temp = temp->next;
    }
  }

}
引用網址:https://home.gamer.com.tw/TrackBack.php?sn=4165899
All rights reserved. 版權所有,保留一切權利

相關創作

留言共 0 篇留言

我要留言提醒:您尚未登入,請先登入再留言

喜歡★as200188 可決定是否刪除您的留言,請勿發表違反站規文字。

前一篇:要是二進位還能被桶 那麼... 後一篇:【心得】C++ clas...

追蹤私訊切換新版閱覽

作品資料夾

hyzgdivina喜歡虹咲的LLer
我的小屋裡有很多又香又甜的Hoenn繪師虹咲漫畫翻譯喔!歡迎LoveLiver來我的小屋裡坐坐~看更多我要大聲說昨天19:30


face基於日前微軟官方表示 Internet Explorer 不再支援新的網路標準,可能無法使用新的應用程式來呈現網站內容,在瀏覽器支援度及網站安全性的雙重考量下,為了讓巴友們有更好的使用體驗,巴哈姆特即將於 2019年9月2日 停止支援 Internet Explorer 瀏覽器的頁面呈現和功能。
屆時建議您使用下述瀏覽器來瀏覽巴哈姆特:
。Google Chrome(推薦)
。Mozilla Firefox
。Microsoft Edge(Windows10以上的作業系統版本才可使用)

face我們了解您不想看到廣告的心情⋯ 若您願意支持巴哈姆特永續經營,請將 gamer.com.tw 加入廣告阻擋工具的白名單中,謝謝 !【教學】