单链表运算

来源:互联网 发布:接入网络方式 编辑:程序博客网 时间:2024/06/18 12:58
#include<stdio.h>#include<malloc.h>typedef int ElemType;typedef struct Node{    ElemType data;    struct Node *next;} SqList;void InitList(SqList *&L){    L=(SqList*)malloc(sizeof(SqList));    L->next=NULL;}void Insert(SqList *L,ElemType a){    SqList *s;    while(L->next!=NULL)    {        L=L->next;    }    s=(SqList *)malloc(sizeof(SqList));    s->data=a;    L->next=s;    s->next=NULL;}bool SqNull(SqList *L){    return(L->next!=NULL);}void Print( SqList *L){    SqList *p=L->next;    while (p!=NULL)    {        printf("%d ",p->data);        p=p->next;    }    printf("\n");}void PrintLength(SqList *L){    SqList *p=L;    int i=0;    while (p->next!=NULL)    {        i++;        p=p->next;    }    printf("%d\n",i);}void PrintData(SqList *L,int i){    int j=0;    ElemType e;    SqList *p=L;    while (j<i && p!=NULL)    {        j++;        p=p->next;    }    if (p!=NULL)    {        e=p->data;        printf("单链表第%d个元素=%d\n",i,e);    }}int Find(SqList *L,ElemType e){    SqList *p=L->next;    int n=1;    while (p!=NULL && p->data!=e)    {        p=p->next;        n++;    }    if (p==NULL)        return(0);    else        return(n);}bool  Insertinto(SqList *&L,int i,ElemType e){    int j=0;    SqList *p=L,*s;    while (j<i-1 && p!=NULL)    {        j++;        p=p->next;    }    if (p==NULL)        return false;    else    {        s=(SqList *)malloc(sizeof(SqList));        s->data=e;        s->next=p->next;        p->next=s;        return true;    }}bool Delete(SqList *&L,int i){    int j=0;    SqList *p=L,*q;    while (j<i-1 && p!=NULL)    {        j++;        p=p->next;    }    if (p==NULL)        return false;    else    {        q=p->next;        if (q==NULL)            return false;        p->next=q->next;        free(q);        return true;    }}int main(){    SqList *L;    InitList(L);    ElemType a,b,c,d,e;    scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);    Insert(L,a);    Insert(L,b);    Insert(L,c);    Insert(L,d);    Insert(L,e);    Print(L);    PrintLength(L);    if(SqNull(L))        printf("单链表不为空\n");    else        printf("单链表为空\n");    PrintData(L,3);    printf("元素a的位置:%d\n",Find(L,a));    ElemType f;    scanf("%d",&f);    Insertinto(L,4,f);    Print(L);    Delete(L,3);    Print(L);    free(L);    return 0;}

0 0
原创粉丝点击