您的位置:首页 > Web前端 > Node.js

[c++] list with head node

2016-10-25 20:29 302 查看
/*
* 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: