#include <cstdio>
#include <malloc.h>
typedef int ElemType;
typedef struct ListNode
{
ElemType Element;
ListNode *next;
} *PNode;
//创建链表
PNode CreateList(void)
{
int len; // 链表长度
int val; //存放链表数值
PNode PHead = (PNode) malloc (sizeof(PNode)); //头结点
PNode PTail = PHead; //尾节点
PTail -> next = NULL;
printf("请输入结点个数\n");
scanf("%d",&len);
for (int i = 0; i < len; i++)
{
PNode PNew = (PNode) malloc (sizeof(PNode));
if (PNew == NULL)
{
printf("分配新节点失败\n");
return 0;
}
printf ("请输入第%d个节点的数据\n",i);
scanf("%d",&val);
PNew -> Element = val;
PTail -> next = PNew;
PNew -> next = NULL;
PTail = PNew;
}
printf ("创建链表成功!\n");
return PHead; //返回头节点
}
//插入元素
void InsertList (PNode p, int pos, int elem)
{
PNode k = (PNode) malloc (sizeof(PNode));
PNode q = p;
for (int i = 0; i< pos - 1; i++)
{
q = q->next;
}
k ->Element = elem;
k-> next = q -> next;
q->next = k;
}
//删除元素
void DeleteList(PNode p, int pos)
{
PNode q = p;
for (int i = 0; i < pos - 1; i++)
{
q = q ->next;
}
q -> next = q -> next ->next;
}
//free链表
void FreeList(PNode p)
{
int i;
while(p != NULL)
{
free(p);
p = p->next;
//printf ("%d\n",i++);
}
}
void Print (PNode p)
{
printf ("输出链表的值\n");
PNode q = p -> next;
while (q != NULL)
{
printf("%d\n",(q -> Element));
q = q ->next;
}
}
int main()
{
ElemType data;
int pos;
PNode List = CreateList();
Print(List);
printf("插入操作,请输入插入的位置和数字\n");
scanf("%d%d",&pos,&data);
InsertList(List,pos,data);
Print (List);
printf("删除操作,输入删除的位置\n");
scanf("%d",&pos);
DeleteList(List,pos);
Print (List);
FreeList(List);
return 0;
}
输出结果
(对有时间学习编程的人士强烈推荐vscode,界面美观,并且能学到很多底层的东西)