slnklist(不带头结点的单链表)

本文介绍了一个简单的单链表实现,包括初始化、插入、删除等核心操作,并通过示例展示了如何使用这些函数来构建和操作单链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
typedef int datatype;


typedef struct link_node {
datatype info;
struct link_node *next;
}node;


node *init()
{
return NULL;
}


void display(node *head)
{
node *p;
p = head;
if (!p)
printf("单链表是空的!");
else
{
printf("依次输出:\n");
while (p)
{
printf("%d\t", p->info);
p = p->next;
}
}
printf("\n");
}


node *find(node *head, int i)
{
int j = 1;
node *p = head;
if (i == 0)
return head;
while (p&&i != j)
{
p = p->next;
j++;
};
if (i != j)
return NULL;
return p;
}


node *insert(node *head, datatype x, int i)
{
node *p, *q;
q = find(head, i);
if (!q)
{
printf("找不到要插入的位置!\n");
}
else
{
p = (node *)malloc(sizeof(node));
p->info = x;
if (i == 0)
{
p->next = head;
head = p;
}
else
{
p->next = q->next;
q->next = p;
}
}
return head;
}


node *find_last(node *head)
{
node *p,*pre;
if (!head)
printf("表是空的!\n");
else
{
p = head;
while (p)
{
pre = p;
p = p->next;
}
return pre;
}
}


node *build(node *head, datatype x)
{
node *q = (node *)malloc(sizeof(node));
q->info = x;
q->next = NULL;
if (!head)
{
head = q;
}
else
{
node *p = find_last(head);
p->next = q;
}
return head;
}


node *dele(node *head, datatype x)
{
node *pre, *p;
if (!head)
printf("表是空的!\n");
else
{
p = head;
if (head->info == x)
{
head = p->next;
free(p);
}
while (p&&p->info != x)
{
pre = p;
p = p->next;
}
if (!p&&pre->info != x)
{
printf("没有找到要删的节点!\n");
}
else
{
pre->next = p->next;
free(p);
}
}
return head;
}


void main()
{
node *N,*head;
head = init();
int i = 0; 
for (i = 0; i < 10; i++)
head = build(head, i * 3);
display(head);
N = find(head, 3);
printf("%d\n", N->info);
head = insert(head, 100, 2);
display(head);
head = insert(head, 200, 0);
display(head);
head = dele(head, 15);
display(head);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值