您的位置:首页 > 其它

自己创建链表类,实现几个基本操作

2015-05-12 21:44 330 查看
/////List 创建 添加 删除
#include <iostream>
#include <string>
#include <stack>
using namespace std;
class Node
{
public:
int Data;
Node*Node_next;
Node():Data(0),Node_next(NULL){}
};

class list
{
Node*head;
public:
list(){head=NULL;}
void insertlist(int iData);//链表尾部插入
void Deletelist(int aDate);//链表结点的删除
void Outputlist();//链表结点的输出
void ReverseOutput();////反向输出
Node*Gethead(){return head;}
};
void list::ReverseOutput()
{
stack<int> stk;
Node* phd = head;
while (phd!= NULL)
{
stk.push(phd->Data);
phd = phd->Node_next;
}
while (!stk.empty())
{
cout<<stk.top()<<" ";
stk.pop();
}
cout<<endl;

}
void list::Deletelist(int iData)
{
if (head != NULL)
{
Node* ptemp = head;
if (head->Data == iData)
{
ptemp = head;
head = head->Node_next;
delete ptemp;
}
else
{
Node* pn = ptemp;
while ((ptemp!= NULL) && (ptemp->Data != iData))
{
pn = ptemp;
ptemp = ptemp->Node_next;
}
if (ptemp->Data == iData)
{
pn->Node_next = ptemp->Node_next;
delete ptemp;
}
}
}
}
void list::insertlist(int iData)
{
Node* pNewNode = new Node();
pNewNode->Data = iData;
if (head == NULL)
{
head = pNewNode;
}
else
{
Node* phd = head;
Node* ptmp = head;
while(phd != NULL)
{
ptmp = phd;
phd = phd->Node_next;
}
ptmp->Node_next = pNewNode;
}
}

void list::Outputlist()
{
Node* phd = head;
while (phd!= NULL)
{
cout<<phd->Data<<" ";
phd = phd->Node_next;
}
cout<<endl;
}

////代码测试
#define LEN 10
int main()
{
list A;
int Data[10]={25,41,16,98,5,67,9,55,1,121};
for (int i=0; i<LEN; i++)
{
A.insertlist(Data[i]); //建立链表
}

cout<<"\n链表A:"<<endl;
A.Outputlist();
A.Deletelist(Data[5]);
cout<<"删除元素Data[5]后"<<endl;
A.Outputlist();
cout<<"删除元素Data[5]后反向输出"<<endl;
A.ReverseOutput();
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐