fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct Cell {
  5. long val;
  6. struct Cell *prev;
  7. struct Cell *next;
  8. };
  9.  
  10. class DoubleLinkedList {
  11. public:
  12. DoubleLinkedList() {
  13. first = NULL;
  14. last = NULL;
  15. }
  16. void ins(long x) {
  17. struct Cell *c = new Cell;
  18. c->val = x;
  19. c->prev = NULL;
  20. c->next = first;
  21. if (first != NULL) { first->prev = c; }
  22. first = c;
  23. if (last == NULL) {
  24. last = c;
  25. }
  26. }
  27. void del(long x) {
  28. struct Cell *p = first;
  29. struct Cell *pPrev;
  30. struct Cell *pNext;
  31. while(p->val != x) {
  32. p = p->next;
  33. if (!p) { return; }
  34. }
  35.  
  36. pPrev = p->prev;
  37. pNext = p->next;
  38. if (pNext) { pNext->prev = pPrev; }
  39. if (pPrev) { pPrev->next = pNext; }
  40. if (p == first) {
  41. first = pNext;
  42. }
  43. if (p == last) {
  44. last = pPrev;
  45. }
  46. delete p;
  47. }
  48. void delFirst() {
  49. struct Cell *p = first->next;
  50. if (p) { p->prev=NULL; }
  51. if (first == last) {
  52. last = NULL;
  53. }
  54. delete first;
  55. first = p;
  56. }
  57. void delLast() {
  58. struct Cell *p = last->prev;
  59. if (p) { p->next = NULL; }
  60. if (last == first) {
  61. first = NULL;
  62. }
  63. delete last;
  64. last = p;
  65. }
  66. void printValues() {
  67. struct Cell *p = first;
  68.  
  69. if (p) {
  70. cout << p->val;
  71. p = p->next;
  72. }
  73. while (p) {
  74. cout << " ";
  75. cout << p->val;
  76. p = p->next;
  77. }
  78. cout << endl;
  79. }
  80. private:
  81. struct Cell *first;
  82. struct Cell *last;
  83. };
  84.  
  85. int main()
  86. {
  87. long n, value;
  88. string cmd;
  89. DoubleLinkedList dll;
  90.  
  91. cin >> n;
  92. for (long i=0; i<n; i++) {
  93. cin>> cmd;
  94. if (cmd == "insert") {
  95. cin >> value;
  96. dll.ins(value);
  97. continue;
  98. }
  99. else if (cmd == "delete") {
  100. cin >> value;
  101. dll.del(value);
  102. continue;
  103. }
  104. else if (cmd == "deleteFirst") { dll.delFirst(); continue; }
  105. else if (cmd == "deleteLast") { dll.delLast(); }
  106. }
  107.  
  108. // outpur values in ddl
  109. dll.printValues();
  110.  
  111. return 0;
  112. }
Success #stdin #stdout 0s 3476KB
stdin
9
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5
deleteFirst
deleteLast
stdout
1