StackList.h内のpushTopがリストの先頭に値を代入してofferが末尾に値を代入するプログラムで、popで先頭の値を出力させるとうにしています。
mainを動かしたときにundefined reference というエラーが出てしまい作動しませんでした。
c++
1//StackCell.h 2#pragma once 3#include <cstdlib> 4#include<sstream> 5template <class Type>class StackCell { 6public: 7 Type value; 8 StackCell* forward; 9 StackCell* backward; 10 StackCell(const Type val = 0) : 11 value(val), forward(NULL), backward(NULL) { 12 } 13}; 14 15//StackList.h 16#pragma once 17#include"StackCell.h" 18#include<sstream> 19template <class Type>class StackList{ 20private: 21 StackCell<Type> *top; 22 StackCell<Type> *tail; 23public: 24 StackList() : 25 top(NULL),tail(NULL){ 26 } 27 void pushTop(Type value); 28 void offer(Type value); 29 Type pop(); 30}; 31 32//StackList.cpp 33#include"StackList.h" 34#include<sstream> 35 36 template<class Type> void StackList<Type>::pushTop(Type v) { 37 StackCell<Type> *tmp = new StackCell<Type>(v); 38 if (top == NULL) { 39 top = tmp; 40 tail = tmp; 41 } else { 42 top->backward = tmp; 43 tmp->forward = top; 44 tmp->backward = NULL; 45 top = tmp; 46 } 47} 48 template<class Type>void StackList<Type>::offer(Type v) { 49 StackCell<Type> tmp = new StackCell<Type>(v); 50 if (tail == NULL) { 51 top = tmp; 52 tail = tmp; 53 } else { 54 tail->forward = tmp; 55 tmp->forward = NULL; 56 tmp->backward = tail; 57 tail = tmp; 58 } 59} 60 template<class Type>Type StackList<Type>::pop() { 61 if (top == NULL) { 62 return -1; // エラー 63 } else { 64 StackCell<Type>* cell = top; 65 top = cell->forward; 66 top->backward = NULL; 67 Type value = cell->value; 68 delete cell; 69 return value; 70 } 71} 72 73//main.cpp 74#include<iostream> 75#include"StackList.h" 76using namespace std; 77int main() { 78 int x; 79 StackList<int> *list = new StackList<int>; 80 list->pushTop(1); 81 list->pushTop(2); 82 x = list->pop(); 83 cout << x << endl; 84 StackList<double> *list2 = new StackList<double>; 85 list2->offer(1); 86 list2->offer(2); 87 list2->offer(3); 88 list2->offer(4); 89 list2->offer(5); 90 list2->offer(6); 91 for (int i = 0; i < 3; i++) { 92 x = list2->pop(); 93 cout << x << endl; 94 } 95 96}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/29 04:57