C语言链表操作简介

(例子)将结构体定义为:

struct ST{
    int n;
    int score;
    struct ST *next;
};

空链表的建立(这里是指含有一个头结点的链表,创建空链表的函数代码如下)

struct ST *CreatNullList()
{
    struct ST *head;
    head=(struct ST *)malloc(sizeof(struct ST));
    if(head!=NULL)
        head->next=NULL;
    else
        printf("Out Of space!\n");
    return head;
};

判断链表是否为空

int IsNullList(struct ST *head)
{
    return head->next==NULL;
}

在链表最后天界一个结点

int Append(struct ST *head,int n,int s)
{
    struct ST *p,*pNew;
    pNew=(struct ST *)malloc(sizeof(struct ST));
    if(pNew==NULL)
    {
        printf("Out of space!\n");
        return 0;
    }
    else{
        pNew->n=n;
        pNew->score=s;
        p=head;
        while(p->next!=NULL)
            p=p->next;
        p->next=pNew;
        pNew->next=NULL;
    }
    return 0;

}

求某结点的指针

struct ST *locate(struct ST *head,int n)//求学号为n的结点的指针
{
    struct ST *p;
    p=head->next;
    while(p!=NULL&&p->n!=n)
        p->next=pNew;
    return p;
}

求P所指结点的前驱(前一个结点)

struct ST *locatePre(struct ST *head,struct ST *p)
{
    struct ST *ptemp;
    ptemp=head;
    while(ptemp!=NULL&&ptemp->next!=p)
        ptemp=ptemp->next;
    return ptemp;
}

在某个结点之后插入一个新节点

int Insert(struct ST *head,struct ST *p,int n,int s)
{
    struct ST *pNew=(struct ST *)malloc(sizeof(struct ST));
    if(pNew==NULL)
    {
        printf("Out of space!\n");
        return 0;
    }
    else{
        pNew->n=n;
        pNew->score=s;
        pNew->next=p->next;
        p->next=pNew;
        return 1;
    }
}

结点的删除

int Delete(struct ST *head,int n)
{
    struct ST *p1,*p2;
    p1=head;
    //下面循环用来插找学号为n的结点的前驱
    while(p1->next!=NULL&&p1->next->n!=n)
        p1=p1->next;
    if(p1->next==NULL)
    {
        printf("Not exist!\n");
        return 0;
    }
    p2=p1->next;//找到了学号为n的结点
    p1->next=p2->next;//将p2所指结点排除到链表之外
    free(p2);//释放p2所指的结构体变量
    return 1;
}

猜你喜欢

转载自blog.csdn.net/Sun_xiangyan/article/details/88428912
今日推荐