单向链表代码程序(2)

来源:互联网 发布:中日关系论断 知乎 编辑:程序博客网 时间:2024/06/05 19:27
#include<stdio.h>
#define N 5
#include<stdlib.h>
#include<string.h>

typedef struct student{
    unsigned id;
    char name[20];
    struct student *next;
}st_t;
st_t *mk_node(int id,char *name)
{
    st_t *p = (st_t *)malloc(sizeof(st_t));
    if(p != NULL){
        p->id = id;
        strcpy(p->name ,name);
        p->next = NULL;
    }
    return p;
}
st_t *insert_tail(st_t *head,int id,char *name)
{
    st_t *newp = mk_node(id,name);
    st_t *tail;
    if(!head||!newp){
        if(!head)
            head = newp;
        return head;
    }
    for(tail = head;tail->next!=NULL;tail=tail->next)
        ;
    tail->next = newp;
    return head;
}
st_t *insert_head(st_t *head,int id,char *name)
{
    st_t *newp = mk_node(id,name);
    if(!head||!newp){
        if(!head)
            head = newp;
        return head;
    }
    newp->next = head;
    head = newp;
    return head;
}


st_t *insert_body(st_t *head,int id,char *name)
{
    st_t *newp = mk_node(id,name);
    st_t *p,*q;
     p =head;
    if(!head||!newp){
        if(!head)
            head = newp;
        return head;
    }
    while(( (p->id)< id)&&((p->next) != NULL))
    {
        q = p;
        p = p->next;
    }
    if(( p->id)> id){
        if(head == p)
            head = insert_head(head,id,name);
        else
        {    
            q->next = newp;
            newp->next = p;
        //    q = q->next;    
        }
    }
    else
        head = insert_tail(head,id,name);
    return head;
}

void link_destroy(st_t *head)
{

    st_t *cur,*next;
    for(cur = head;cur;cur = next){
        next = cur -> next;
        free(cur);    
    }
}

void link_print(st_t *head)
{
    st_t *cur;

    for(cur = head;cur!=NULL;cur = cur->next)
        printf("%d %s\n",cur->id,cur->name);
    printf("\n");
}

int main(void)
{
    st_t *head = NULL;
    int i;
    char name[20];
    int  id;
    //st_t stu[N];
    for(i =0;i<N;i++)
    {
        printf("shu ru:");
        scanf("%d%s",&id,name);
        head = insert_body(head,id,name);
    }
    link_print(head);
    return 0;
}
            

  


插入节点代码也可以简化成如下代码


node_t *insert_body(node_t *head,int n)
{
    node_t *newp = mk_node(n);
    node_t *p,*q;
     p =head;
    if(!head||!newp){
        if(!head)
            head = newp;
        return head;
    }
    for(pre = cur = head; cur && cur->item<n; )
    {
        pre = cur;
        cur = cur->next;
    }
    if(cur == head){
        newp->next = head;
        head=newp;
    }
    else{
        newp->next = cur;
        pre->next = newp;
    }
    return head;
}

原创粉丝点击