您的位置:首页 > 其它

链表的顺序插入 先分析有几种类型再编写 思路要清晰

2013-08-17 21:08 246 查看
//P339链表的实现

#include "MyList.h"

struct node* Insert(struct node* head,int x)//head中的数据都排好序  小到大  x按顺序插入

{

    struct node * q=head,*pre;

    struct node * newnode=(struct node*) malloc(sizeof(struct node));

    newnode->data = x;

    if(head==NULL)

    {

        head = newnode;

        head->next=NULL;

        return head;

    }

    while(q!=NULL)

    {

        if(q->data>=x) break;

        pre = q;

        q=q->next;

    }

    if(q==head)//头结点插入

    {

        head = newnode;

        newnode->next=q->next;

    }

    else //非头节点

    {

        pre->next=newnode;

        newnode->next = q;

    }

    return head;

}

int main()

{

    struct node * head = NULL;

    int x;

    while (scanf("%d",&x)==1)

    {

        head=Insert(head,x);

        printf("列表成员如下:\n");

        Print(head);

    }

    DelMemory(head);

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐