单链表的基础实现

本文介绍了一个使用C语言实现的单链表基本操作案例,包括创建、打印、插入和删除节点等核心功能,并提供了完整的代码及运行结果。

单链表基础实现
时间:2006/03/23
测试环境:TC2.0

#include <stdio.h>
#define LEN sizeof(struct LNode)
#define NULL 0

typedef int ElemType;

struct LNode
{
ElemType data;
struct LNode *next;
};

/*创建一个带空头结点的单链表*/
struct LNode *CreatList()
{
struct LNode *head,*p,*temp;
head = (struct LNode *)malloc(LEN);
p = temp = (struct LNode *)malloc(LEN);
printf("input the number:");
scanf("%d",&p->data);
head->next = p;
while(p->data!=0)
{
p = (struct LNode *)malloc(LEN);
printf("input the number:");
scanf("%d",&p->data);
temp->next = p;
temp = p;
}
temp->next = NULL;
return head;
}

/*打印出单链表*/
void Print(struct LNode *head)
{
struct LNode *p;
p = head->next;

while(p->next!=NULL)
{
printf("%d ",p->data);
p = p->next;
}

}
/*销毁这个线性表*/
void DestroyList(struct LNode *head)
{
struct LNode *p,*temp;
p = temp = head->next;
while(head->next!=NULL)
{
head->next = p->next;
temp = p;
free(temp);
p = head->next;
}
}

/*在第i个位置前插入新结点*/
void InsertList(struct LNode *head,int i)
{
struct LNode *p,*insert;
int count = 0;
p = head;
while(count<i-1 && p)
{
count++;
p = p->next;
}
if(count>i-1 || !p)
return;
printf("input a number that you want to insert:");
insert = (struct LNode *)malloc(LEN);
scanf("%d",&insert->data);
insert->next = p->next;
p->next = insert;
}

/*删除第i个结点*/
void DeleteList(struct LNode *head,int i)
{
struct LNode *p,*temp;
int count = 0;
p = head;
while(count<i-1 && p)
{
count++;
p = p->next;
}
if(count>i-1 || !p)
return;
temp = p->next;
p->next = temp->next;
free(temp);
}

void main()
{
struct LNode *L;
/*创建链表并打印*/
L = CreatList();
printf("your list is:/n");
Print(L);
printf("/n");
/*在第3个结点前插入新结点,并打印*/
InsertList(L,3);
printf("now,your list is:/n");
Print(L);
printf("/n");
/*删除第4个结点,并打印*/
printf("delete the 4th member,");
printf("now,your list is:/n");
/*销毁链表,并验证是否成功*/
DeleteList(L,4);
Print(L);
DestroyList(L);
if(!L->next)
printf("/nyour list has destroyed!");
}

运行后结果:

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值