单向链表插入、删除及查找算法

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*宏定义
*/
#define True 1
#define False 0
typedef int Status;
typedef int ElemType;
typedef struct Lnode {
ElemType date;//数据域
struct Lnode *next;
}LNode;
/*函数声明
*/
void Build_List(LNode *L);
Status GetElem_L(LNode *L, int insert, ElemType *Date);
void Exit(void);
LNode * HCreateList_T(void);
void Output_List(LNode *L);
LNode *LocateFun(LNode *L, ElemType Date);
Status Insert_List(LNode *L, int insert, ElemType Date);
/*主函数
*/
int main(void){
ElemType date;
LNode *List = HCreateList_T();
Output_List(List);
printf(“check two position and print…\r\n”);
GetElem_L(List, 2, &date);
printf("%d\r\n",date);
system(“pause”);
return 0;
}
/*开辟新的链表单元
*/
void Build_List(LNode L) {
L= (LNode
)malloc(sizeof(LNode));//开辟内存空间
}
/*创建链表
*/
LNode *HCreateList_T(void) {
int num;
LNode p = (LNode)malloc(sizeof(LNode));
LNode *temp = p;
printf(“please input build num…\r\n”);
scanf("%d",&num);
for (int i = num; i >0; i–) {
LNode a = (LNode)malloc(sizeof(LNode));
printf(“please input date…\r\n”);
scanf("%d", &a->date);
a->next = NULL;
temp->next = a;
temp = temp->next;
}
return p;
}
/*检验insert是否存在
*@param *L
*@return status
*/
Status GetElem_L(LNode *L, int insert, ElemType *Date) {
int j=1;
LNode *p;
p = L->next;
while (p&&j<insert) {
p = p->next;
j++;
}
if (!p || j >insert) {
return False;
}
*Date=(*p).date;
return True;
}
/*插入链表元素
*@param:insert
*@param:Date
*@if successful,return true
*/
Status Insert_List(LNode *L,int insert,ElemType Date) {
LNode *p;
LNode NewCell;
int i;
p = L->next;
for (i=0; i <insert-1; i++){
p = p->next;
}
if (!p)Exit();
Build_List(&NewCell);
NewCell.date = Date;
NewCell.next = p->next;
p->next =&NewCell;
return True;
}
/*删除链表元素
*attention:if not free space,maybe unknow mistake
*/
ElemType Dele_List(LNode *L, int insert) {
LNode *p,*TemporarySpace;
ElemType Date;
p = L->next;
for (int i = 0; i <insert-1; i++)
{
p = p->next;
}
if (!(p->next))Exit();
TemporarySpace =p->next;
Date = p->next->date;
p->next = TemporarySpace->next;
free(TemporarySpace);//free insert space
return Date;
}
/*按值查找
*/
LNode *LocateFun(LNode *L, ElemType Date) {
LNode *p;
p = L->next;
while (p&&p->date!=Date)
{
p = p->next;
}

return p;//返回找寻到的p地址

}

/*错误
*/
void Exit(void) {
printf(“Error,Please try again…\r\n”);
}
/*打印当前链表
*/
void Output_List(LNode *L) {
LNode *p=L;
printf(“List out:\r\n”);
printf(“List={”);
while (p->next) {
p= p->next;
printf(" {%d} “, p->date);
}
printf(”}");
printf("\r\n");

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值