数据结构复习到队列,顺手写了个链队列demo,以链表类的形式存储队列,队列中的最小单位是节点Node结构体,考虑到链表在表头插入时间开销最小,为O(1),而进队列是在队尾完成,故把头结点作为队尾,尾结点作为队头,把进队列和出队列操作分别对应成链表的插入和删除函数。
debug过程中碰到两个主要问题,似乎不是第一次犯的错了,记下来加深印象:
1.定义数据成员Top和成员函数top的时候,不要弄重名!!!
2.在写进队和出队函数时,不能仅仅用一行insert or Delete代替,因为链表插入或删除节点后,表头和表尾都可能改变,所以要再次更新队头和队尾!!!
代码附上:
#includeusing namespace std; typedef struct Node { int data; Node* next; Node(int x) { data = x; next = NULL; } }Node; class list { public: Node* head; Node* tail; list(int x) { head = new Node(x); tail = head; } void insert(int x) { Node* tmp = new Node(x); if (head == NULL) { head = tmp; tail = head; } else { tmp->next = head; head = tmp; } } void Delete() {//删除尾结点 if (head == NULL) return; if (head == tail) head = tail = NULL; else { Node* tmp = head; while (tmp->next!=tail) tmp = tmp->next; delete tail; tail = tmp; } } }; class Queue { public: Node* Top;//队头 Node* back;//队尾 list* pl; Queue(int x) { pl = new list(x); back = pl->head; Top = pl->tail; } void push(int x) { pl->insert(x); back = pl->head; Top = pl->tail; } void pop() { pl->Delete(); back = pl->head; Top = pl->tail; } int top() { if (Top != NULL) return Top->data; else return 0; } bool empty() { return Top == NULL; } }; int main() { Queue* pq=new Queue(1); pq->push(3); pq->push(5); pq->push(7); pq->push(10); while(!pq->empty()) { int x = pq->top(); cout << x << " "; pq->pop(); } }



