#include<stdlib.h>
#include<string.h>
#include<stdio.h>
typedef struct LNode
{
int data;
struct LNode* next;
}LNode, * LinkList;
LinkList List_H(LinkList& L) //头插法插入元素
{
LNode* s;
int x;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
printf("请输入链表元素的值(输入-1结束)\n:");
scanf_s("%d", &x);
while (x != -1)
{
s = (LNode*)malloc(sizeof(LNode));
s->next = NULL;
s->data = x;
s->next = L->next;
L->next = s;
scanf_s("%d", &x);
}
return L;
}
LinkList List_T(LinkList& L) { //尾插法循环插入元素
LNode* s, * r;
int x;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
r = L;
printf("请输入链表中元素的值:(输入9结束)\n");
scanf_s("%d", &x);
while (x != 9)
{
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
s->next = NULL; //最后一个元素末尾置空;
r->next = s;
r = s;
scanf_s("%d", &x);
}
return L;
}
LinkList PrintfList(LinkList L) //打印元素
{
LNode* p;
p = L->next; //p指向第1号元素
if (p == NULL)
printf("NULL");
else
printf("打印链表中的元素:");
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
return L;
}
LNode* GetElem(LinkList L, int i) //查找第i号元素;
{
int j = 1;
LNode* p = L->next;
if (i == 0) //头节点输出NULL;
printf("NULL");
if (i < 0) //不合理值处理
printf("NULL");
while (p != NULL && j < i)
{
p = p->next;
j++;
}
return p;
}
LNode* Getdata(LinkList L, int e)
{
LNode* p = L->next;
while (p!= NULL && p->data != e)
{
p = p->next;
}
return p;
}
int LengthLink(LinkList L)
{
int len = 0;
LNode* p = L;
while (p->next != NULL)
{
p=p->next;
len++;
}
return len;
}
int main() //主函数
{
LinkList L;
L = (LinkList)malloc(sizeof(LNode));
while(1)
{
printf("\n请输入接下来的操作:\n");
printf("1:创建表,输入元素并打印元素\n");
printf("2:寻找第i号元素并打印\n");
printf("3:寻找元素x\n");
printf("4:求表长\n");
printf("5:打印链表中所有元素:\n");
printf("-1:退出\n\n");
int x;
scanf_s("%d", &x);
int n,len;
int elem;
LNode* i, * p;
if (x == -1)
break;
switch (x)
{
case 1:
List_T(L);
printf("\n");
break;
case 2:
printf("查找第几号元素:");
scanf_s("%d", &n);
printf("\n打印出第%d号元素:", n);
i = GetElem(L, n);
printf("%d", i->data);
printf("\n");
break;
case 3:
printf("输入需要查找的元素:");
scanf_s("%d", &elem);
p = Getdata(L, elem);
printf("\n找到了");
printf("%d", p->data);
printf("\n");
break;
case 4:
len = LengthLink(L);
printf("\n表长:%d", len);
printf("\n");
break;
case 5:
printf("链表中元素所有的值为:");
PrintfList(L);
break;
}
}
}