码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-05-12 22:32:39      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

/////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;
}

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

标签:

原文地址:http://www.cnblogs.com/niupan369/p/4498723.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!