数据结构学习中的简单问题(一):用链表方式实现的队列输出杨辉三角
2013-04-11 00:42 liuzq2013 阅读(427) 评论(0) 收藏 举报之前没怎么花时间,面临数据结构考试了,看了一天的数据结构,把链表,栈,队列都看了一遍,写点示例程序加深一下印象。
template <class T> struct QueueNode { T data; QueueNode<T> *link; QueueNode(T d = 0, QueueNode<T> *next = NULL) : data(d), link(next) { } }; template <class T> class LinkedQueue { private: QueueNode<T> *front, *rear;//队头、队尾指针 public: LinkedQueue() : rear(NULL), front(NULL) { } ~LinkedQueue(); bool EnQueue(T x); //x加入队列 bool DeQueue(T& x); //删除队头元素,x返回其值 bool GetFront(T& x); //查看队头元素的值 void MakeEmpty(); //置空队列 bool IsEmpty() const { return front == NULL; } bool IsFull() const { return false; } }; template <class T> LinkedQueue<T>::~LinkedQueue() {//析构函数 QueueNode<T> *p; while (front != NULL) {//逐个结点释放 p = front; front = front->link; delete p; } }; template <class T> bool LinkedQueue<T>::EnQueue(T x) { QueueNode<T> *newNode=new QueueNode<T>(x); if(front==NULL){ front=newNode; rear=newNode; if(front==NULL) return false; } else{ rear->link=newNode; if (rear->link == NULL) return false; rear=newNode; } return true; }; template <class T> bool LinkedQueue<T>::DeQueue(T& x) { if(front==NULL) return false; QueueNode<T> *del=front; front=front->link; x=del->data; delete del; return true; }; template <class T> bool LinkedQueue<T>::GetFront(T& x) { if(front==NULL) return false; x=front->data; return true; };
主程序:
#include <iostream> #include "LinkedQueue.h" using namespace std; int main() { LinkedQueue<int> q; int n=1,t=1,u=0,s=0; q.EnQueue(n); q.EnQueue(n); cin>>n;//n represents the number of lines to be display cout<<1<<" "<<1<<endl;//Print the first line for(int i=1;i<n;i++){ s=0;q.EnQueue(s);//s saves the value that is deleted from the queue in the last round for(int j=0;j<i+2;j++){ q.DeQueue(t);//t saves the value that is deleted from the queue in this round u=s+t;q.EnQueue(u); s=t;//let s=t,for the preparation of next round cout<<u<<" "; } cout<<endl; } }
浙公网安备 33010602011771号