#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef int Elemtype;
//节点定义
typedef struct LNode
{
Elemtype data;
struct LNode* next;
}LNode, * LinkList;
//头插法
void List_head_insert(LinkList& head)
{
//申请头节点
head = (LNode*)malloc(sizeof(LNode));
head->next = NULL;
//定义新节点
LinkList s;
//要插入的数据
Elemtype x;
scanf("%d", &x);
//插入数据非9999的节点
while (x != 9999)
{
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
s->next = head->next;
head->next = s;
scanf("%d", &x);
}
}
//尾插法
void List_tail_insert(LinkList& head)
{
head = (LinkList)malloc(sizeof(LNode));
head->next = NULL;
LinkList s, r = head; //s为新节点,r为尾节点
Elemtype x;
scanf("%d", &x);
while (x != 9999)
{
s = (LinkList)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
scanf("%d", &x);
}
r->next = NULL;
}
//按位置查找
LinkList LocateElem(LinkList& head, int SearchPos)
{
LinkList s = head->next;
int i = 1;
if (i < 0)
{
return NULL;
}
while (s && i <= SearchPos)
{
if (i == SearchPos)
{
return s;
}
s = s->next;
i++;
}
return NULL;
}
//按值查找
LinkList Getelem(LinkList& head, Elemtype SearchVal)
{
LinkList s = head->next;
while (s)
{
if (s->data == SearchVal)
{
return s;
}
s = s->next;
}
return NULL;
}
//在第i个位置插入数据
bool ListFrontInsert(LinkList head, int i, Elemtype InsertVal)
{
if (i < 1)
{
return false;
}
//找到第i-1的位置
LinkList p= LocateElem(head,i-1);
//新节点
LinkList s;
s = (LinkList)malloc(sizeof(LNode));
s->data = InsertVal;
s->next = p->next;
p->next = s;
return true;
}
//删除第i个位置的元素
bool ListDelete(LinkList head, int i)
{
if (i < 1)
{
return false;
}
//找到第i-1的位置
LinkList p = LocateElem(head, i - 1);
//第i的位置的节点
LinkList q = p->next;
p->next=q->next;
free(q);
return true;
}
//打印链表
void Print_List(LinkList& head)
{
LinkList s;
s = head->next;
while (s != NULL)
{
printf("%d ", s->data);
s = s->next;
}
printf("\n");
}
int main()
{
//定义头结点
LinkList head1;
LinkList head2;
//头插
List_head_insert(head1);
Print_List(head1);
//尾插
List_tail_insert(head2);
Print_List(head2);
//位置查找
LinkList t1 = LocateElem(head1, 1);
if (t1 == NULL)
{
printf("该位置不存在\n");
}
else
{
printf("该位置的值为%d\n", t1->data);
}
//值查找
LinkList t2 = Getelem(head1, 5);
if (t2)
{
printf("该元素存在\n");
}
else
{
printf("该元素不存在\n");
}
//在第i个位置插入数据
if (ListFrontInsert(head1, 2, 999))
{
printf("插入成功\n");
}
else
{
printf("插入失败\n");
}
Print_List(head1);
//删除第i个位置的数据
if (ListDelete(head1, 2))
{
printf("删除成功\n");
}
else
{
printf("删除失败\n");
}
Print_List(head1);
return 0;
}
(王道练习代码仓库)单链表 ———— C语言
于 2024-10-07 17:22:23 首次发布