单链表——The headless singly linked list

本文提供了一个使用C语言实现的链表操作示例,包括创建、插入、查找、删除及显示链表等基本功能。通过具体代码展示了如何进行链表的基本管理和数据处理。

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

#include <stdio.h>
#include <stdlib.h>
#include "list.h"

int main()
{
int i;
DATA x;
LIST head = NULL;
head = ListCreate();
if(NULL == head)
{
return 1;
}
for(i = 0;i < 6; i++)
{
x = i + 3;
//ListInsertHead(head,&x);
ListInsertTail(head,&x);
}
x = 5;
PtrNode p = ListFind(head,&x);
if(p == NULL)
{
printf("not find value!\n");
}
else
{
printf("data = %d\n",p->data);
}
ListDelete(head,&x);
ListDisplay(head);
ListDistroy(head);
return 0;
}

#ifndef _LIST_H__
#define _LIST_H__

struct node;
typedef int DATA;
typedef struct node * LIST;
typedef struct node * PtrNode;
typedef struct node * Position;

LIST ListCreate();
int ListIsEmpty(LIST);
int ListMakeEmpty(LIST);
int ListIsLast(LIST,Position);
int ListInsert(LIST,Position,const DATA *);
int ListInsertHead(LIST,const DATA *);
int ListInsertTail(LIST,const DATA *);
PtrNode ListFind(LIST,const DATA *);
PtrNode ListFindPrev(LIST,const DATA *);
int ListDelete(LIST,const DATA *);
void ListDisplay(LIST);
void ListDistroy(LIST);

struct node{
DATA data;
struct node * next;
};
#endif

#include <stdio.h>
#include <stdlib.h>
#include "list.h"

LIST ListCreate()
{
PtrNode head = malloc(sizeof(*head));
if(head == NULL)
{
return NULL;
}
ListMakeEmpty(head);
return head;
}

int ListIsEmpty(LIST l)
{
return l->next == NULL;
}
int ListMakeEmpty(LIST l)
{
l->next = NULL;
}
int ListIsLast(LIST l,Position p)
{
return p->next == NULL;
}
int ListInsert(LIST l,Position prev,const DATA * data)
{
PtrNode cur = malloc(sizeof(*cur));
if(cur == NULL)
{
return 2;
}
cur->data = *data;
cur->next = prev->next;
prev->next = cur;

return 0;
}
int ListInsertHead(LIST l,const DATA * data)
{
return ListInsert(l,l,data);
}
int ListInsertTail(LIST l,const DATA * data)
{
Position tail = l;
for(;tail->next != NULL;tail = tail->next);
return ListInsert(l,tail,data);
}
PtrNode ListFind(LIST l, const DATA *data)
{
PtrNode p = l->next;
for(;p != NULL && p->data != *data;p = p->next);
return p;
}
PtrNode ListFindPrev(LIST l,const DATA *data)
{
PtrNode p = l;
for(;p->next != NULL && p->next->data!=*data;p=p->next);
return p;
}
int ListDelete(LIST l,const DATA *data)
{
Position prev = ListFindPrev(l,data);
if(!ListIsLast(l,prev))
{
Position q = prev->next;
prev->next = q->next;
free(q);
return 0;
}
return -1;
}

void ListDisplay(LIST l)
{
Position p = l->next;
while(p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
putchar('\n');
}
void ListDistroy(LIST l)
{
Position p = l->next;
Position q;

while(p != NULL)
{
q = p;
p = p->next;

free(q);
}
free(l);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值