#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
typedef int Status;
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode, *LinkList;
// 对链表进行初始化
Status InitList_L(LinkList &L){
L = (LNode *)malloc(sizeof(LNode));
if(L == NULL) return ERROR;
L->next = NULL;
return OK;
}
// 插入数据
Status ListInsert_L(LinkList &L, int i, ElemType e){
LNode *p=L,*s;
int j=0;
while(p && j<i-1)
{
p=p->next;
j++;
}
if(!p||j>i-1) return ERROR;
s=(LinkList)malloc(sizeof(LNode));
s->data=e;
s->next=p->next;
p->next=s;
return OK;
}
// 头插法
Status ListPreInsert(LinkList &L, int i, ElemType e){
if(i < 1) return ERROR;
int j = 1;
LinkList s = (LNode *)malloc(sizeof(LNode));
if(s == NULL) return ERROR;
LinkList p = (LNode *)malloc(sizeof(LNode));
p = L;
while(p != NULL && j < i){
p = p->next;
j++;
}
s->next = p->next;
p->next = s;
s->data = p->data;
s->data = e;
return OK;
}
// 尾插法
Status ListEndInsert(LinkList &L, int i, ElemType e){
if(i < 1) return ERROR;
int j = 1;
LinkList s = (LNode *)malloc(sizeof(LNode));
if(s == NULL) return ERROR;
LinkList p = (LNode *)malloc(sizeof(LNode));
p = L->next;
while(p != NULL && j < i){
p = p->next;
j++;
}
s->data=e;
s->next = p->next;
p->next = s;
return OK;
}
// 删除数据
Status ListDelete_L(LinkList L, int i, ElemType &e){
LNode *p;
p = L; int j = 0;
while(p && j < i - 1){
p = p->next;
j++;
}
if(!p->next) return ERROR;
LinkList q;
q = p->next;
p->next = q->next;
e = q->data;
free(q);
}
// 查询数据是否存在
Status LocateElem_SL(LinkList L, ElemType e){
LinkList p;
p = L->next;
while(p != NULL && p->data != e)
p = p->next;
if (p->data){
e = p->data;
printf("数据中存在:%d\n", e);
}
return OK;
}
// 计算链表长度
Status ListLength(LinkList L){
int len = 0;
LinkList p;
p = L;
while(p->next != NULL){
p = p->next;
len++;
}
printf("线性表长度是:%d", len);
return OK;
}
// 打印数据
Status GetElem_L(LinkList L){
LNode *p = L->next;
while(p != NULL){
printf("%d ", p->data);
p = p->next;
}
return OK;
}
int main() {
LinkList L;
InitList_L(L);
while (true){
printf("请输入插入数据的个数:\n");
int n;
scanf("%d", &n);
printf("请输入要插入的数据:\n");
CreatList_L(L,n);
printf("打印结果如下:\n");
GetElem_L(L);
printf("\n");
ListInsert_L(L, 3, 25);
GetElem_L(L);
printf("\n");
printf("请输入要插入之前的元素位置:\n");
int pn, pnum;
scanf("%d %d", &pn, &pnum);
ListPreInsert(L, pn, pnum);
GetElem_L(L);
printf("\n");
printf("请输入要插入之后的元素位置:\n");
int m, num;
scanf("%d %d", &m, &num);
ListEndInsert(L, m, num);
GetElem_L(L);
printf("\n");
ListLength(L);
printf("\n");
int ch;
scanf("%d", &ch);
LocateElem_SL(L, ch);
InitList_L(L);
printf("\n");
}
return 0;
}
c语言数据结构之单链表基本操作
最新推荐文章于 2021-05-21 17:30:35 发布