代码
#include<iostream>
using namespace std;
struct node
{
int e; //链表成员的e存放数值 ,头结点的e存放链表成员个数(即总结点数 )
node* next; //next指针存放下一个结点的地址
};
//在第n位插入新节点(注意是“插入”)
void insertlist(node* head, int n, int shu)
{
if (n<1 || n>head->e + 1) //i的合法位置为1—e+1(i为e+1时是在链尾插入)
{ //该函数是e+1 而不是e
cout << "error"<<endl; //与其他函数不同,写代码时要多留意
return;
}
node* p = head;
for (int i = 1; i < n; i++) //注意是从i=1开始,且i<n没有=号
p = p->next; //假设n=1,即在第一位插入,此时没有进行循环
//因为第一位就是跟在头结点后面的
node* s = new node{ shu,0 };
s->next = p->next;//语句1 //注意语句1要写在语句2前
p->next = s; //语句2 //如果先写语句2的话,就会导致语句1相当于s->next=s然后一直循环
head->e++; //注意head->e(结点个数)要加一
}
void creatlist1(node* head)
{
int n, shu;
cin >> n; //n为结点数
for (int i = 1; i <= n; i++)
{
cin >> shu;
insertlist(head, i, shu); //如果要一直在头结点后放数据可以把i改为1
//此处不用head->e++,因为insertlist已经有了
}
}
//creatlist函数代码较为简洁,但是效率不够高,因为是双循环,
//下面的creatlist2为单循环效率会高一些
void creatlist2(node* head) //该方法作图比较容易理解
{
int n, shu;
cin >> n;
node* p = head;//语句1
for (int i = 1; i <= n; i++)
{
cin >> shu;
node* s = new node{ shu,0 };
s->next=p->next;//语句2 //此语句可以省略
p->next = s;//语句3
p = s;//语句4
head->e++; 注意head->e(结点个数)要加一
}
}//如果是在头结点后面插入的话,则删去语句1、4,并把语句2、3中的p改为head
//查找第n个结点并返回数值
void searchlist1(node* head,int n)
{
if (n<1 || n>head->e)
{
cout << "error" << endl;
return;
}
node* p = head;
while (n--)
p = p->next;
cout << p->e << endl;
}
//查找数值为shu的结点并返回指向该结点的指针
node* searchlist2(node* head, int shu)
{
node* p = head;
while (p) //最后一个结点的p->next为0,会将p变为0(即空指针NULL)
{
if (p->e = shu)
return p;
p = p->next;
}
return 0; //若没有找到则返回空指针
}
//删除第n个结点
void deletelist(node* head, int n)
{
if (n<1 || n>head->e)
{
cout << "error" << endl;
return;
}
node* p = head;
for (int i = 1; i < n; i++)
p = p->next; //让p指向第n-1个结点
node* s = p->next;
p->next = s->next; //相当于 p->next=p->next->next;
delete s;
head->e--; //注意要减一
}
//输出链表
void showlist(node* head)
{
node* p = head->next; //头结点并不算是链表的第一个结点,故让p指向第一个结点
while (p->next)
{
cout << p->e << " ";
p = p->next;
}
cout << p->e << endl; //注意补上最后一个
}
//删除链表
void destroylist(node* head)
{
node* p;
while (head->next)
{
p = head->next;
head->next = p->next;
delete p;
}
delete head;
}
int main()
{
node* head = new node{ 0,0 };
creatlist1(head);
showlist(head);
insertlist(head,3,100);
showlist(head);
deletelist(head, 2);
showlist(head);
destroylist(head);
}
(by 归忆)