[c++] list with head node

来源:互联网 发布:java获取tomcat根目录 编辑:程序博客网 时间:2024/05/17 13:11
/* * g++ ListTest.cpp -o L * valgrind ./L */#include <stdio.h>#include <stdlib.h>struct ListNode{ListNode* pNext;int Value;};class IntList{public:IntList() throw(){m_Front.pNext=NULL;m_Front.Value=-1;m_pRear = &m_Front;}~IntList() throw(){ListNode *p = m_Front.pNext;while(p!=NULL){m_Front.pNext=p->pNext;free(p);p=m_Front.pNext;}}bool Empty() const throw() {return m_Front.pNext==NULL;}void Push(int v) throw(){ListNode *p = (ListNode*) malloc(sizeof(ListNode));if(p!=NULL){p->pNext=NULL;p->Value=v;m_pRear->pNext=p;m_pRear=p;}}int Front() const throw(){if(m_Front.pNext!=NULL) return m_Front.pNext->Value;else return -1;}int Rear() const throw(){return m_pRear->Value;}void Pop() throw(){ListNode *p=m_Front.pNext;if(p!=NULL){m_Front.pNext=p->pNext;free(p);if(m_Front.pNext==NULL) m_pRear=&m_Front;}}private:ListNode m_Front;ListNode* m_pRear;};int main(){IntList int_list;int index=0;for(int i=0;i<100;++i) int_list.Push(i);while(int_list.Empty()==false){if(int_list.Front()!=index){printf("Error, index=%d,Front()=%d",index,int_list.Front());}printf("value = %d\n",int_list.Front());index = int_list.Front()+1;int_list.Pop();}for(int i=0;i<100;++i) int_list.Push(i);return 0;}

0 0