单链表的定义,插入,删除,读取(二级指针,一级指针的应用)

来源:互联网 发布:it教育培训 编辑:程序博客网 时间:2024/06/08 01:48


#include <stdio.h>
#include <stdlib.h>
#define Ok 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node *next;
}Node;
typedef Node* Linklist;


void InitList(Linklist *Lp)    //这里*Lp就是头指针,Lp是头指针的地址,*Lp为二级指针,之所以用二级指针是因为之后要修改头指针的地址,形参改变实参的值必须用地址来传
{
*Lp=NULL;
printf("初始化成功!建立一个空链表\n");   //初始化用二级指针是因为我们要把头指针指向空,修改了头指针
}


Status InsertList(Linklist *Lp,int pos,ElemType e)
{
if (pos<0)
{
printf("pos is wrong\n" );
return ERROR;
}


Node *p=(Node *)malloc(sizeof(Node));
if (p==NULL)
{
printf("malloc failed!\n");
return ERROR;
}
p->data=e;
if(pos==1)
    {
    p->next=*Lp;/*顺序不能颠倒*/
    *Lp=p;
    }
    else
    {
    int i=1;
    Linklist L=*Lp;
    
    while (L!=NULL&&i<pos-1)
    {
    L=L->next;
    i++;
    }
    if (L==NULL)
    {
    printf("pos is wrong!\n" );
    free(p);
    return ERROR;
    }
    p->next=L->next;
    L->next=p;
}
return Ok;
}


Status DeleteList(Linklist *Lp,int pos,ElemType *e)
{
if (pos<=0)
{
printf("pos is wrong \n");
return ERROR;
}
if (*Lp==NULL)
{
printf("the list is NULL!\n");
return ERROR;
}
if (pos==1)
{
Linklist L=*Lp;
*e=L->data;
*Lp=L->next;
free(L);
}
else
{
int i=1;
Linklist L=*Lp;
while(L!=NULL&&i<pos-1)
{
L=L->next;
i++;
}
if (L==NULL)
{
printf("pos is wrong\n");
return ERROR;
}
*e=L->next->data;
Linklist pt=L->next;
L->next=L->next->next;
free(pt);
}
return Ok;
}
Status GetElem(Linklist L,int pos,ElemType *e)  //查看不需要用二级指针,因为不需要修改主函数内的链表
{
int i=1;
if (pos<=0)
{
printf("pos is wrong\n" );
return ERROR;
}
while(L!=NULL&&i<pos)
{
i++;
L=L->next;
}
if (L==NULL)
{
printf("没有该位置上的元素\n");
return ERROR;
}
else
{
*e=L->data;
return Ok;
}
}
Status printlist(Linklist L)
{
if (L==NULL)
{
printf("nothing in the list \n");
return ERROR;
}
while(L!=NULL)
{
printf("%d\n",L->data);
L=L->next;
}
printf("\n");
return Ok;
}


int main()
{
 Linklist L1;
    InitList(&L1);
    while(1)
    {
        int sel,pos;
        ElemType e;
        printf("\t\t欢迎使用顺序表!\n");
        printf("\t\t菜单\n");
        printf("\t\t1:插入模式\n");
        printf("\t\t2:显示顺序表\n");
        printf("\t\t3:退出程序\n");
        printf("\t\t4:删除模式\n");
        printf("\t\t5:查询模式\n");
        scanf("%d",&sel);
        switch(sel)
        {
            case 1:
                 printf("请输入待插位置和元素\n");
                 scanf("%d %d",&pos,&e);
                 InsertList(&L1,pos,e);
                break;
            case 2:
                 printlist(L1);
                break;
            case 3:
                 return 0;
            case 4:
            printf("输入要删除的位置\n");
            scanf("%d",&pos);
            DeleteList(&L1,pos,&e);
            break;
            case 5:
            printf("输入查询的位置\n");
            scanf("%d",&pos);
            GetElem(L1,pos,&e);
            printf("查询到得数是:%d\n",e);
        }
}
return 0;
}
原创粉丝点击