#include<stdio.h>
#include<stdlib.h>
#define DES 10
typedef struct node
{
int data;
struct node *next;
}LNode, *LinkList;
LNode *Creat_LinkListEnd()//头插法建立链表
{
LNode *ptr=(LNode *)malloc(sizeof(LNode));
//LinkList ptr = (LinkList)malloc(sizeof(LNode));
ptr->next = NULL;
LNode *s,*p;
p = ptr;
int num;
scanf("%d", &num);
while (num != DES)
{
s = (LNode *)malloc(sizeof(LNode));
s->data = num;
s->next = NULL;
p->next = s;
p = s;
scanf("%d", &num);
}
return ptr;
}
LNode *Creat_LinkListHead()//尾插法建立链表
{
LNode *ptr = (LNode *)malloc(sizeof(LNode));
ptr->next = NULL;
LNode *s, *p;
p = ptr;
int num;
scanf("%d", &num);
while (num != DES)
{
s = (LNode *)malloc(sizeof(LNode));
s->data = num;
s->next = p->next;
p->next = s;
scanf("%d", &num);
}
return ptr;
}
int Length_LinkList(LNode *L)//求链表的长度
{
int length = 0;
LNode *p = L;
while (p->next)
{
p = p->next;
length++;
}
return length;
}
LNode *Find_Position(LNode *L, int pos)//按位查找
{
int i = 0;
LNode *p = L;
while (p->next != NULL&&i < pos)
{
p = p->next;
i++;
}
if (i == pos)
return p;
else
return NULL;
}
LNode *Find_Element(LNode *L, int x)//按元素查找
{
LNode *p = L->next;
while (p&&p->data != x)
{
p = p->next;
}
return p;
}
void Printf_LinkList(LNode *L)//遍历链表
{
LNode *p=L;
p = p->next;
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int Insert_Element(int x, int pos, LNode *L)//插入元素
{
LNode *p, *s;
p = Find_Position(L, pos - 1);
if (p == NULL)
return 0;
else
{
s = (LNode *)malloc(sizeof(LNode));
s->data = x;
s->next = p->next;
p->next = s;
return 1;
}
}
int Delete_Element(int pos, LNode *L)//删除元素
{
LNode *p, *s;
p = Find_Position(L, pos-1);
if (p == NULL||p->next == NULL)
return 0;
else
{
s = p->next;
p->next = s->next;
free(s);
return 1;
}
}
int main()
{
LNode *L,*P;
int length,i=1,x=100;
L = Creat_LinkListEnd();
length = Length_LinkList(L);
printf("链表长=%d\n", length);
P = Find_Position(L, i);
P = Find_Element(L, x);
Printf_LinkList(L);
Insert_Element(x, i, L);
length = Length_LinkList(L);
printf("链表长=%d\n", length);
Printf_LinkList(L);
Delete_Element(i, L);
length = Length_LinkList(L);
printf("链表长=%d\n", length);
Printf_LinkList(L);
system("pause");
return 0;
}
线性表的链式结构
最新推荐文章于 2021-04-06 23:29:04 发布