计算机中没有现成的节点,我们需要自己创建它。任意的节点都包含了两部分:左边部分data存储数据,右边部分next存储指针,单链表的动态创建,查找,遍历,删除,插入,添加,排序 收藏:
#include<iostream.h>
typedef struct node //定义一个结构体,在c++中也是一个类
{
int val;
struct node* pNext;
}NODE,*PNODE;
/DE == struct node 定义一个新的接点
//PNODE == struct node* 定义一个指向这个接点的指针
class MyList //创建一个类
{
private:
PNODE pHead;//struct node* pHead
public:
MyList() //构造函数,构造一个空链表头指针
{
this->pHead = NULL;
}
~MyList() //析构函数
{
while(this->pHead!=NULL)
{
PNODE pTemp = pHead->pNext;
delete pHead;
pHead = pTemp;
}
}
void Init() //初始化链表
{
int a;
char ans;
PNODE pTail,pNew;
do
{
cout<<"请输入一个节点值:";
cin>>a;
if(pHead == NULL)//判断链表中是否有元素(是否是空链表)
{
pHead = new NODE;
pHead->val = a;
pHead->pNext = NULL;
pTail = pHead;
}
else
{
pTail = pHead;
while(pTail->pNext!=NULL)//把pTail移动到尾部
{
pTail = pTail->pNext;
}
pNew = new NODE;//new一个新的接点来接受新输入的值
pNew->val = a;
pNew->pNext = NULL;
pTail->pNext = pNew;
pTail = pTail->pNext;
}
cout<<"继续吗?(Y/N): ";
cin>>ans;
}while(ans=='Y'||ans=='y');
}
void Add(int val) //向链表中追加值方法
{
if(pHead == NULL)
{
pHead = new NODE;
pHead->val = val;
pHead->pNext = NULL;
}
else