#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct node {
ElemType data;
struct node *next;
}Node;
typedef Node* PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
//判断是否是空链表
int IsEmpty(List L) {
return L->next == NULL;
}
//判断是否是末尾
int IsLast(Position P, List L) {
return P->next == NULL;
}
//寻找
Position Find(ElemType X, List L) {
Position P;
P = L->next;
while (P != NULL && P->data != X) {
P = P->next;
}
return P;
}
Position FindPrevious(ElemType X, List L) {
Position P;
P = L;
while (P->next != NULL && P->next->data != X) {
P = P->next;
}
return P;
}
void Delete(ElemType X, List L) {
Position P, Tmp;
P = FindPrevious(X, L);
if (!IsLast(P,L)) {
Tmp = P->next;
P->next = Tmp;
free(Tmp);
}
}
//根据位置来插入元素
void InSert(ElemType X, List L, Position P) {
Position TmpCell;
TmpCell = (List)malloc(sizeof(Node));
if (TmpCell == NULL) {
printf("Out of space!!!");
}
TmpCell->data = X;
TmpCell->next = P->next;
P->next = TmpCell;
}
//输出链表
void PrintList(List L) {
Position P;
P = L;
while (P != NULL) {
printf("%d ", P->data);
P = P->next;
}
printf("\n");
}
//创建链表
List CreatedList() {
Position head, p1, p2;
int n;
p2 = p1 = (Node*)malloc(sizeof(Node));
if (p1 == NULL) {
printf("Can not create p1!!!");
return NULL;
}
else {
head = NULL;
n = 0;
printf("请输入数据:");
scanf_s("%d", &(p1->data));
while (p1->data != 0) {
n++;
if (n == 1) {
head = p1;
p2->next = NULL;
}
else {
p2->next = p1;
}
p2 = p1;
p1 = (struct node*)malloc(sizeof(struct node));
printf("请输入数据:");
scanf_s("%d", &(p1->data));
}
p2->next = NULL;
free(p1);
p1 = NULL;
return head;
}
}
//删除链表
void DeLeteList(List L) {
Position P, Tmp;
P = L->next;
L->next = NULL;
while (P != NULL) {
Tmp = P->next;
free(P);
P = Tmp;
}
}
//生成空链表
List MakeEmpty(List L) {
L = (struct node*)malloc(sizeof(struct node));
L->data = 0;
L->next = NULL;
return L;
}
//返回头结点
Position Header(List L) {
return L;
}
//返回第一个数据节点的位置
Position First(List L) {
if (L->next != NULL)
return L->next;
}
//获得位置P后继节点位置
Position Advance(Position P) {
if (P != NULL)
return P->next;
}
//返回P位置的数据
ElemType Retrieve(Position P) {
if (P != NULL)
return P->data;
}
单链表的函数声明和定义
猜你喜欢
转载自blog.csdn.net/weixin_37378399/article/details/78806691
今日推荐
周排行