Implement a queue/stack

Queue:

Doubly linked list:

#include <iostream>
using namespace std;

struct ListNode {
  int val;
  ListNode *next, *pre;
  ListNode(int x) :val(x), next(NULL), pre(NULL) {}
};

class Queue {
  private: ListNode *first, *last;
  public:
  Queue() {first=NULL; last=NULL;}
  void add(int value);
  int remove();
};

void Queue::add(int value) {
  if (!first) {
    last = new ListNode(value);
    first = last;
  }else {
    ListNode *newNode = new ListNode(value);
    last->next = newNode;
    newNode->pre = last;
    last = last->next;
  }
}

int Queue::remove() {
  int res=0;
  if (first) {
    res = first->val;
    first = first->next;
    return res;
  }
  return 0;
}

// Should print:
// 1
// 2
// 3
int main() {
  cout << "Starting\n";
  Queue q;
  q.add(1);  
  q.add(2);
  cout << q.remove() << "\n";
  q.add(3);
  cout << q.remove() << "\n";
  cout << q.remove() << "\n";
  return 0;
}


Singly  linked list : 1->2->3

#include <iostream>
using namespace std;

struct ListNode {
  int val;
  ListNode *next;
  ListNode(int x) :val(x), next(NULL) {}
};

class Queue {
  private: ListNode *first, *last;
  public:
  Queue() {first=NULL; last=NULL;}
  void add(int value);
  int remove();
};

void Queue::add(int value) {
  if (!first) {
    last = new ListNode(value);
    first = last;
  }else {
    ListNode *newNode = new ListNode(value);
    last->next = newNode;
    last = last->next;
  }
}

int Queue::remove() {
  int res=0;
  if (first) {
    res = first->val;
    first = first->next;
    return res;
  }
  return 0;
}

Stack:

Singly linked list 3->2->1

#include <iostream>
using namespace std;

struct ListNode {
  int val;
  ListNode *next;
  ListNode(int x) :val(x), next(NULL) {}
};

class Stack {
  private: 
  //vector<int> items;
  //int num;
  ListNode *top;
  public:
  Stack() {top = NULL;}
  void add(int value);
  int remove();
};

void Stack::add(int value) {
  if (!top) {
    top = new ListNode(value);
  }else {
    ListNode *newNode = new ListNode(value);
    newNode->next = top;
    top = newNode;
  }
}

int Stack::remove() {
  int res=0;
  if (top) {
    res = top->val;
    top = top->next;
    return res;
  }
  return 0;
}

// Should print:
// 2
// 3
// 1
int main() {
  cout << "Starting\n";
  Stack s;
  s.add(1);
  s.add(2);
  cout << s.remove() << "\n";
  s.add(3);
  cout << s.remove() << "\n";
  cout << s.remove() << "\n";
  return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值