引言
头插法
尾插法
按位置查找
按值查找
在第i个位置插入元素
代码
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;//数据域
struct LNode* next;//指向下一个结点
}LNode,*LinkList;
/*
在给定的代码中,typedef int ElemType;
定义了一个新的类型名 ElemType,它是 int 类型的别名。
同样地,typedef struct LNode LNode;
定义了一个新的类型名 LNode,它是 struct LNode 类型的别名。
接下来,typedef struct LNode* LinkList;
定义了一个新的类型名 LinkList,它是 struct LNode* 类型的别名。
这意味着 LinkList 是指向 LNode 结构体的指针类型。
*/
//头插法新建链表
//LNode*是结构体指针,和LinkList完全等价的
//由于在创建是定义了struct LNode* 类型的指针,
//所以在使用是LinkList是结构体指针类型的指针变量
//但是这个结构体别名又叫做LNode所以linklist=LNode*
void ListHeadInsert(LNode* &L)
{
LNode* s;//用来指向申请的新结点
ElemType x;
L =(LNode*)malloc(sizeof(LNode));//申请头结点空间,头指针指向头结点
L->next = NULL;
scanf("%d", &x);
while (x != 9999)
{
//输入4 5 6 7 9999
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
s->next=L->next;
L->next = s;
scanf("%d", &x);
}
}
//尾插法
void ListTailInsert(LinkList &L)
{
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
ElemType x;
scanf("%d", &x);
LNode* s,*r=L;//LinkList s,r=L也是可以的。
//s用来指向新结点,r始终指向链表尾
while (x!=9999)
{
s = (LinkList)malloc(sizeof(LNode));
s->data = x;
r->next = s;//新节点给尾结点的next指针
r = s;
scanf("%d", &x);
}
r->next = NULL;
}
//打印链表
void PrintList(LinkList L)
{
L = L -> next;
while (L!= NULL)//判断结点L是否为空
{
printf("%3d",L->data);
L = L->next;
}
printf("\n");
}
//按照位置查找
LinkList GetElem(LinkList L,int SearchPos)
{
int i = 0;
if (SearchPos < 0)
{
return NULL;
}
while (L&&i < SearchPos)
{
L = L->next;
i++;
}
return L;
}
//按值查找
LinkList LocateElem(LinkList& L, ElemType searchVal)
{
L=L->next;
while (L)
{
if (L ->data == searchVal)
{
return L;
}
L = L->next;
}
return L;
}
//往第i个位置插入元素
bool ListFrontInsert(LinkList L, int i, ElemType InsertVal)
{
LinkList p = GetElem(L, i - 1);
if (NULL == p)
{
return false;
}
LinkList q= (LinkList)malloc(sizeof(LNode));
q->data = InsertVal;
q->next = p->next;
p->next = q;
return true;
}
//删除第i个位置的元素
bool ListDelete(LinkList L, int i)
{
LinkList p=GetElem(L,i-1);//拿到要删除的结点的前一个结点
if (NULL==p)
{
return false;
}
LinkList q=p->next;//拿到p的下一个结点
p->next = q->next;
free(q);
return true;
}
int main()
{
LinkList L,search;//链表头指针,是结构体指针类型
ListHeadInsert(L);
PrintList(L);
ListTailInsert(L);
PrintList(L);
//按位置查找
search=GetElem(L,2);
if (search != NULL)
{
printf("查找成功\n");
printf("位置上的值为%d\n", search->data);
}
search=LocateElem(L, 3);
if (search != NULL)
{
printf("查找成功\n");
printf("位置上的值为%d\n", search->data);
}
ListFrontInsert(L, 2, 99);
PrintList(L);
ListDelete(L, 6);
PrintList(L);
return 0;
}