单链表的实现

#include<stdio.h>
#include<stdlib.h>

//创建一个单链表
struct LNode                //结点
{
    int data;               //数据
    struct LNode* next;     //指向下个结点的指针   
};


void List_Print(struct LNode* p)//自定义列表打印函数
{
    while(p)
    {
        printf("%d ",p->data);
        p = p->next;
    }
    printf("\n");
}

void List_Insert(struct LNode* p,int i,int e)//插入操作。在表L中的第i个位置上插入指定元素。
{
    struct LNode* q;
    q=p;//将头结点地址保存
    for(int j=0;(j<i-1)&&(q!=NULL);j++)//找到第i的前面那个结点
    {
        q=q->next;
    }
    struct LNode* s=(struct LNode*)malloc(sizeof(struct LNode));
    s->data=e;  //将数值写入
    s->next=q->next; //将i-i的后继结点的指针(也就是i的头指针),赋值给要插入结点的后继
    q->next=s;//将原本指向i结点的后继指针,改为指向插入结点的头指针
}


struct LNode* Build_List()//头插法建立单链表
{
    struct LNode *s,*p,*r;
    p=(struct LNode*)malloc(sizeof(struct LNode));
    p->data=0;
    r=p;
    int x;
    scanf("%d",&x);
    while (x!=999)
    {
        s=(struct LNode*)malloc(sizeof(struct LNode));
        s->data=x;
        p->next=s;
        p=s;
        scanf("%d",&x);
    }
    p->next=NULL;
    return r;
}


void List_Delete(struct LNode* p,int i) //删除操作。将单链表中的第i个元素去除。
{
    struct LNode* r;
    r=p;
    for(int j=0;j<i-1;j++)//找到i-1个结点的后继
    {
        r=r->next;
    }
    struct LNode* s;
    s=r->next;//临时保存要删除的结点,以用来释放
    r->next=r->next->next;//将指针跳过第i个
    free(s);
}

void List_Find(struct LNode* p,int data)//查找,
{

}


void Start(struct LNode* p)
{
    int n;
    printf("***********1-Build_List***********\n");
    printf("***********2-List_Insert**********\n");
    printf("***********3-List_Delete**********\n");
    printf("***********4-List_Print***********\n");
    while (1)
    {
        printf("Input\n");
        scanf("%d",&n);
        switch (n)
        {
        case 1:p=Build_List();break;
        case 2:List_Insert(p,2,89);break;
        case 3:List_Delete(p,5) ;break;
        case 4:List_Print(p);break;    
        }
    }
}


int main()
{
    struct LNode* p; //一个指向单链表的指针
    Start(p);
    return 0;
}
posted @ 2023-07-22 15:21  风恬月淡时  阅读(21)  评论(0)    收藏  举报