#include <stdio.h>
#include <stdlib.h>
typedef struct Lnode
{
int data;
struct Lnode *next;
} Lnode, *Linklist;
main()
{
Linklist L, p, q, m;
int n, i, j, e;
p = (Linklist)malloc(sizeof(Lnode));
p->next = NULL; //建立头结点
L = p;
n = 10; //给单链表赋初值
for (i = 0; i < n; i++)
{
q = (Linklist)malloc(sizeof(Lnode)); //生成新结点
q->data = i + 1;
q->next = NULL;
p->next = q;
p = p->next;
}
printf("Lnode:");
m = L->next;
while (m)
{
printf("%d,", m->data);
m = m->next;
}
printf("\n"); //输出单链表
//在第i个位置插入值为e的新结点
p = L;
i = 1;
e = 10;
j = 0;
printf("\n在第%d个位置上,插入元素e=%d\n", i, e);
while (p && j < i - 1)
{
p = p->next;
++j;
} //寻找第i-1个结点
if (!p || j > i - 1)
printf("ERROR!\n");
q = (Linklist)malloc(sizeof(Lnode));
q->data = e;
q->next = p->next;
p->next = q;
printf("\ninsert:"); //输出插入e后的单链表
q = L->next;
while (q)
{
printf("%d,", q->data);
q = q->next;
}
printf("\n");
//删除第i个位置上的值,并返回值e
i = 2;
p = L;
j = 0;
printf("\n删除第%d个位置上的元素\n", i);
while (p->next && j < i - 1)
{
p = p->next;
++j;
} //寻找第i-1个结点
if (!(p->next) || j > i - 1)
printf("ERROR!\n");
q = p->next;
p->next = q->next;
e = q->data;
free(q);
printf("\nDeleted element:e=%d\n", e);
printf("\ndelete:"); //输出删除元素后的单链表
q = L->next;
while (q)
{
printf("%d,", q->data);
q = q->next;
}
printf("\n");
}
用c语言实现单链表的建立、插入与删除
于 2022-03-23 14:50:40 首次发布