程序代码:
#include"stdio.h"
#include"stdlib.h"
#include<iostream>
using namespace std;
typedef struct node{//定义链表结点
int data;
struct node*next;
}lnode,*listptr;
listptr generatelist(int n)//生成一个长度为n的链表
{
listptr list = NULL, p = NULL, r = NULL;
int e = 0;
for (int i = 0; i < n; i++)
{
p = (listptr)malloc(sizeof(lnode));//生成一个结点
cin >> e;
p->data = e;//对此结点数据域和指针域赋值
p->next = NULL;
if (!list)//当链表为空时
list = p;
else//当链表不为空时
r->next = p;
r = p;
}
return list;
}
void insertelem(listptr*list, listptr q, int elem)//向链表中q结点后面插入结点
{
listptr p = (listptr)malloc(sizeof(lnode));
p->data = elem;
if (!*list)//list是指向头结点的指针的指针,如果链表为空
{
*list = p;
p->next = NULL;
}
else//链表不为空
{
p->next = q->next;
q->next = p;
}
}
void deleteelem(listptr*list, listptr q)//将链表中q结点删除
{
if (*list == q)//如果q结点为头结点
{
*list = q->next;
free(q);
}
else//如果q结点不为头结点,又不知q结点的前驱结点
{
listptr p;
for ( p= *list; p->next != q; p = p->next);//遍历链表,寻找q结点的前驱结点
if (p->next != NULL)
{
p->next = q->next;
free(q);
}
}
}
void destroylist(listptr*list)//销毁一个链表
{
listptr p = *list;
listptr r;
while (p)//从头结点开始,依次销毁每一个结点
{
r = p->next;
free(p);
p = r;
}
*list = NULL;
}
int main()
{
listptr l, q;
l = q = generatelist(1);//生成链表
int e;
cin >> e;
while (e)//插入元素
{
insertelem(&l, q, e);
q = q->next;
cin >> e;
}
q = l;//打印出链表中的所有元素
printf("\nthe content of the list is:\n");
while (q)
{
printf("%d", q ->data);
q = q ->next;
}
q = l;//删除链表中的第5个元素
for (int i = 0; i < 4; i++)//使q指向链表中第5个元素
{
if (q == NULL)
{
return 0;
}
q = q->next;
}
deleteelem(&l, q);
q = l;
printf("\nthe content of the list is:\n");
while (q)
{
printf("%d", q->data);
q = q->next;
}
destroylist(&l);
system("pause");
return 0;
}
结果: