线性表的链式结构

#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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>