注意: LinkList L 于 LinkList &L 的区别,前者只能改变指针指向的内容,后者同时还可以修改指针本身,即指针内部
#include
#include
#include
typedef int ElemType;
typedef int Status;
//定义结构体
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode, *LinkList;
//建立单链表
LinkList CreateList(int n)
{
LinkList L = (LinkList)malloc(sizeof(LinkList)); //建一个头结点并初始链表
L->next = NULL;
int x, i;
LinkList r = L;
printf("input %d value:", n);
for (i = 0; i < n; i++)
{
scanf_s("%d", &x);
LinkList p = (LinkList)malloc(sizeof(LinkList));
p->data = x;
p->next = NULL;
r->next = p;
r = r->next;
}
return L;
}
//查找第i个元素并赋给e
Status GetElem_L(LinkList &L, int i, ElemType &e)
{
LinkList p = L->next;
int j = 1;
while (p&&j < i)
{
p = p->next;
++j;
}
if (!p || j > i)
return 0;
e = p->data;
return 1;
}
//在第 i 个位置插入 e
Status InsertList(LinkList &L, int i, ElemType e)
{
LinkList p = L;
int j = 0;
while (p&&j < i - 1)
{
p = p->next;
++j;
}
if (!p || j > i - 1)
return 0;
LinkList s = (LinkList)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return 1;
}
//删除第 i 个位置的元素,并将值保存于 e
Status DeleteList(LinkList &L, int i, ElemType &e)
{
LinkList p = L;
int j = 0;
while (p->next&&j < i - 1)
{
p = p->next;
++j;
}
if (!(p->next) || j > i - 1)
return 0;
LinkList q = p->next;
p->next = q->next;
e = q->data;
free(q); //注意一定要释放内存空间
return 1;
}
//输出单链表
void Output(LinkList L)
{
LinkList p = L->next;
printf("output element:\n");
for (; p != NULL; p = p->next)
{
printf("%d ", p->data);
}
printf("\n");
}
//主函数
int main()
{
LinkList L;
int n,i;
ElemType e;
printf("enter the length of the list:");
scanf_s("%d", &n);
L = CreateList(n);
Output(L); //输出单链表
printf("enter the number you want to find:"); //查找
scanf_s("%d", &i);
GetElem_L(L, i, e);
printf("the %d number is %d\n", i, e);
printf("please enter the number and element you want to insert:"); //插入
scanf_s("%d %d", &i, &e);
InsertList(L, i, e);
Output(L);
printf("please enter the number and element you want to delete:"); //删除
scanf_s("%d %d", &i, &e);
DeleteList(L, i, e);
Output(L);
system("pause");
return 0;
}