如何实现单向链表的首尾添加

来源:互联网 发布:数据挖掘最优算法 编辑:程序博客网 时间:2024/06/05 07:08
#include <iostream>


using namespace std;


struct Node
{
int data;
Node *p_next;
};


class Clist
{
public:
Node *m_pHead;


Clist()
{
m_pHead = NULL;
}


void AddHead(int date)
{
Node *p = new Node;
p->data = date;
p->p_next = m_pHead;
m_pHead = p;
}


void AddTail(int date)
{
Node *p = new Node;
p->data = date;
p->p_next = NULL;
while (m_pHead == NULL)
{
m_pHead = p;
return;
}
Node *p1 = m_pHead;
while (p1->p_next != NULL)
{
p1 = p1->p_next;
}
p1->p_next = p;
}


void Print()
{
Node *pNode = m_pHead;
while (pNode != NULL)
{
cout << pNode->data << endl;
pNode = pNode->p_next;
}
}


int GetCount()
{
Node *pNode = m_pHead;
int n_count = 0;
while (pNode != NULL)
{
cout << pNode->data << endl;
pNode = pNode->p_next;
n_count ++;
}
return n_count;
}
};


int main()
{
Clist list1;
list1.AddHead(31);
list1.AddHead(32);
list1.AddHead(33);
list1.AddTail(34);
list1.AddTail(35);
list1.AddTail(36);


list1.Print();
system("pause");
return 0;
}
0 0