AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

AcWing 827. 双链表 C++    原题链接    简单

作者: 作者的头像   张立斌 ,  2019-10-25 19:38:22 ,  所有人可见 ,  阅读 920


1


1

main函数

#include <cstring>
#include <iostream>
#include <vector>
using namespace std;

int main(void) {
  int m, k, x;
  char oper[4];
  scanf("%d", &m);
  StaticDList dList;
  for (int i = 0; i < m; ++i) {
    scanf("%2s", oper);
    if (!strcmp("L", oper)) {
      scanf("%d", &x);
      dList.pushFront(x);
    } else if (!strcmp("R", oper)) {
      scanf("%d", &x);
      dList.pushBack(x);
    } else if (!strcmp("D", oper)) {
      scanf("%d", &k);
      dList.erase(k);
    } else if (!strcmp("IL", oper)) {
      scanf("%d%d", &k, &x);
      dList.insertBefore(k, x);
    } else if (!strcmp("IR", oper)) {
      scanf("%d%d", &k, &x);
      dList.insertAfter(k, x);
    }
  }
  for (int i = dList.beginIndex(); i != dList.endIndex(); i = dList.nextIndex(i)) {
    printf("%d ", dList[i]);
  }
  puts("");
  return 0;
}

双链表

class StaticDList {
  struct ListNode {
    int prev;
    int next;
    int value;
  };

 public:
  explicit StaticDList(int capacity = 64) {
    nodeVec.reserve(capacity);
    nodeVec.push_back({0, 0, 0});
  }
  void pushFront(int value) { insertAfter(0, value); }
  void pushBack(int value) { insertBefore(0, value); }
  void insertBefore(int index, int value) {
    const int n = nodeVecSize();
    nodeVec.push_back({nodeVec[index].prev, index, value});
    nodeVec[nodeVec[index].prev].next = n;
    nodeVec[index].prev = n;
  }
  void insertAfter(int index, int value) {
    const int n = nodeVecSize();
    nodeVec.push_back({index, nodeVec[index].next, value});
    nodeVec[nodeVec[index].next].prev = n;
    nodeVec[index].next = n;
  }
  void erase(int index) {
    nodeVec[nodeVec[index].prev].next = nodeVec[index].next;
    nodeVec[nodeVec[index].next].prev = nodeVec[index].prev;
  }
  inline int beginIndex() const { return nodeVec[0].next; }
  inline int endIndex() const { return 0; }
  inline int prevIndex(int index) const { return nodeVec[index].prev; }
  inline int nextIndex(int index) const { return nodeVec[index].next; }
  inline int &operator[](int index) { return nodeVec[index].value; }

 private:
  inline int nodeVecSize() const { return nodeVec.size(); }
  vector<ListNode> nodeVec;
};

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息