















代码实现
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode
{
int data;
struct LNode* next;
}LNode, * LinkList;
//创建头结点
LNode* InitList(LinkList L)
{
L = (LNode*)malloc(sizeof(LNode));
if (L == NULL)
{
printf("申请头结点失败\n");
return NULL;
}
L->data = 0;
L->next = NULL;
return L;
}
//判断链表为空
void Empty(LinkList L)
{
if (L->next == NULL)
{
printf("链表为空\n");
}
else
{
printf("链表不为空\n");
}
}
//按位序插入——指定节点的后插操作
//在第i个位置处插入元素e
int ListInsert(LinkList L, int i, int e)
{
if (i < 1)
{
printf("选择插入数据的位序错误\n");
return 1;
}
LNode* p; //指针p指向当前扫描到的节点
int j = 0; //j说明p当前指向的是第几个节点
p = L; //L指向头结点,头结点是第0个节点
while (p != NULL && j < i - 1) //循环指向需要插入的前一个位置
{
p = p->next;
j++;
}
if (p == NULL)
{
return 1;
}
LNode* s = (LNode*)malloc(sizeof(LNode)); //申请一个新节点
s->data = e; //给新节点赋值
s->next = p->next; //将新节点连接到p之后
p->next = s;
return 0;
}
//输出链表
int Print(LinkList L)
{
LNode* P = (LNode*)malloc(sizeof(LNode));
if (P == NULL)
{
printf("开辟空间失败\n");
return 1;
}
P = L;
while (P->next) //P->不为空
{
P = P->next; //将指针指向头结点的下一位
printf("%d ", P->data);
}
return 0;
}
//指定节点的前插操作
int InsertPriorNode(LinkList L, int e)
{
if (L == NULL)
{
return 1;
}
LNode* s = (LNode*)malloc(sizeof(LNode));
if (s == NULL)
{
return 1;
}
s->next = L->next;
L->next = s; //在要前插的节点后新增一个节点
s->data = L->data; //将要前插节点的数据赋值给新增节点
L->data = e; //将原来节点的数据域赋值为要前插的值
return 0;
}
//按位序删除
//删除第i个位置的节点,该节点的数据为e
int ListDelete(LinkList L, int i, int* e)
{
if (i < 1)
{
printf("需要删除的位序错误\n");
return 1;
}
LNode* p;
int j = 0;
p = L;
while (p != NULL && j < i - 1)
{
p = p->next;
j++;
}
if (p = NULL)
{
printf("创建指针p失败\n");
return 1;
}
if (p->next == NULL)
{
printf("要删除的节点不存在\n");
return 1;
}
LNode* q;
q = p->next; //令q指向被删除的节点
*e = q->data; //用e返回元素的值
p->next = q->next; //将q节点从链表中断开
free(q); //释放节点的存储空间
return 0;
}
int main()
{
LinkList L = (LNode*)malloc(sizeof(LNode));
InitList(L);
int i, e;
scanf("%d", &i);
for (int j = 1; j <= i; j++)
{
scanf("%d", &e);
ListInsert(L, j, e);
}
Print(L); return 0;
}