#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef int Elemtype;
typedef struct LNode {
Elemtype data;
struct LNode* next;
}LNode,*LinkList;
LinkList HeadLinkList(LinkList& L) {
L = (LNode*)malloc(sizeof(LNode));
LinkList s;
int x;
scanf("%d",&x);
while (x != 999) {
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
s->next = L->next;
L->next = s;
scanf("%d", &x);
}
return L;
}
LinkList EndLinkList(LinkList& L) {
L = (LNode*)malloc(sizeof(LNode));
LinkList s,r=L;//R是表尾节点
int x;
scanf("%d", &x);
while (x != 999) {
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
scanf("%d", &x);
}
r->next = NULL;
return L;
}
LNode* GetELem(LinkList L,Elemtype i) {
LinkList p = L->next;
int j = 1;
if (i == 0)
return L;
if (i < 1)
return NULL;
while (p && j < i)
{
p = p->next;
j++;
}
return p;
}
LinkList LocateElem(LinkList L, Elemtype e) {
LinkList p = L;
while (p!=NULL && p->data!= e)
p = p->next;
return p;
}
LinkList DeleteList(LinkList& L, Elemtype i) {//根据序号删除指定节点
LinkList p = GetELem(L, i-1);
LinkList q = p->next;
//printf("%d\n", q->data);
p->next = q->next;
free(q);
return L;
}
LNode* InsertList(LinkList& L, Elemtype i) {
LinkList p = GetELem(L, i - 1);
LinkList s = (LNode*)malloc(sizeof(LNode));
Elemtype x;
printf("please input insert in:\n");
scanf("%d", &x);
s->data = x;
s->next = p->next;
p->next = s;
return L;
}
void PrintList(LinkList L) {
L = L->next;
while (L != NULL) {
printf("%3d", L->data);
L = L->next;
}
printf("\n");
}
int main(){
LinkList L;
LinkList search;
LinkList locate;
LinkList del;
//printf("请输入节点:\n");
//HeadLinkList(L);
//printf("你所创建的头插单链表是:\n");
//PrintList(L);
printf("请输入节点:\n");
EndLinkList(L);
printf("你所创建的尾插单链表是:\n");
PrintList(L);
printf("输入需要查找的序号的值:\n");
Elemtype i;
scanf("%d", &i);
search = GetELem(L, i);
if (search != NULL) {
printf("success:\n");
printf("%d\n", search->data);
}
int e;
printf("please input locateElem:\n");
scanf("%d", &e);
locate = LocateElem(L, e);
if (locate != NULL) {
printf("sucess:\n");
printf("%d\n", locate->data);
}
Elemtype in;
printf("please input in:\n");
scanf("%d", &in);
LinkList insert;
insert = InsertList(L, in);
printf("new Linklist:\n");
PrintList(insert);
Elemtype d;
printf("please input delete:\n");
scanf("%d", &d);
del = DeleteList(L, d);
PrintList(del);
return 0;
}
数据结构---单链表的基础操作(增删改查)
最新推荐文章于 2024-09-11 02:02:22 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)