单向链表编写代码

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

typedef struct node{
    int item;
    struct node *next;
}node_t;

node_t *mk_node(int n)
{
    node_t *p = (node_t*)malloc(sizeof(node_t));
    if(p!=NULL){
        p->item = n;
        p->next=NULL;
    }
    return p;
}

node_t *insert_tail(node_t *head,int n)
{
    node_t *newp = mk_node(n);
    node_t *tail;

    if(!head||!newp){
        if(!head)
            head = newp;
        
        return head;
    }
    for(tail = head;tail->next!= NULL;tail = tail->next)
        ;
//    tail->item = n;
    tail->next=newp;
    return head;
}
node_t *insert_head(node_t *head,int n)
{
    node_t *newp = mk_node(n);
    if(!head||!newp){
        if(!head)
            head = newp;
        return head;
    }
    newp->next = head;
    head = newp;
}
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;
    }
    while((n>p->item)&&(p->next!=NULL))
    {
        q = p;
        p = p->next;
    }
    if(n < p->item){
        if(p = head)
            head = insert_head(head,n);
        else
        {
            newp->next = p;
            q->next = newp;
            q = q->next;    
        }
    }
    else
        head = insert_tail(head,n);
    return head;
}


#if 0
node_t *insert_body(node_t *head,int n)
{
    node_t *newp = mk_node(n);
    node_t *p,*q;
    q = p = head;
    if(!head||!newp){
        if(!head)
            head = newp;
        return head;
    }
    if(p->next == NULL)
    {
        if(p->item > newp->item)
            head = insert_head(head,n);
        else
            head = insert_tail(head,n);
    }
    else if(p->item > newp->item)
        {
        head = insert_head(head,n);
        return head;
        }
    for(p = p->next;p != NULL;p=p->next,q=q->next)
    {
        if(p->item > newp->item)
        {
            newp->next = p;
            q->next = newp;
            q = q->next;
        }
    }
    return head;
}
#endif
void link_destroy(node_t *head)
{

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

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

    for(cur = head;cur!=NULL;cur = cur->next)
        printf("%d",cur->item);
    printf("\n");
}
int main(void)
{
    node_t *head = NULL;
    int n;

    while(1){
        scanf("%d",&n);
        if(n==0)
            break;
    //    head = insert_tail(head,n);
        head = insert_body(head,n);
    }
    link_print(head);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值