ITeye博客

链表按序插入节点

zy3381 · 2014-03-14 11:07 · 算法代码收藏 · 编程语言 · Markdown

在一个有序的链表上插入一个节点,使得插入节点后的链表仍然有序


#include<stdio.h>
#define N 5
struct Node
{
    int data;
    struct Node *next;
};

//创建链表并初始化数据
struct Node *create()
{
    int i;
    struct Node *head,*p1,*p2;
    head = p1 = p2 = (struct Node*)malloc(sizeof(struct Node));
    head->data = 89101;
    for(i=1; i<N; i++)
    {
        p1 = (struct Node*)malloc(sizeof(struct Node));
        p1->data = 89102+2*i-1;
        p2->next = p1;
        p2 = p1;
    }
    p2->next = NULL;
    return head;
}

//插入一个节点
void insert(struct Node *head, struct Node *p)
{
    struct Node *pt = head;
    int temp;
    while(pt != NULL)
    {
        if(p->data < pt->data)
        {
            break;
        }
        pt = pt->next;
    }
    //将找到的大于p中的数据值的节点和p的数据进行交换
    temp = pt->data;
    pt->data = p->data;
    p->data = temp;
    //现在pt存储的是p的数据,p存储的是pt的数据,构造连接pt->p->
    p->next = pt->next;
    pt->next = p;
}

void main()
{
    int i;
    struct Node *head,*pt;
    //创建一个链表
    head = pt = create();
    //创建一个新节点
    struct Node *p;
    p = (struct Node*)malloc(sizeof(struct Node));
    p->data = 89102;
    printf("链表初始数据:\n");
    while(pt)
    {
        printf("%d\n", pt->data);
        pt = pt->next;
    }

    printf("\n插入节点%d:\n", p->data);
    //插入链表
    insert(head, p);

    pt = head;
    while(pt)
    {
        printf("%d\n", pt->data);
        pt = pt->next;
    }


    //插入一个节点
    p = (struct Node*)malloc(sizeof(struct Node));
    p->data = 89106;

    printf("\n插入节点%d:\n", p->data);
    insert(head, p);

    pt = head;
    while(pt)
    {
        printf("%d\n", pt->data);
        pt = pt->next;
    }

    //插入一个节点
    p = (struct Node*)malloc(sizeof(struct Node));
    p->data = 89107;

    printf("\n插入节点%d:\n", p->data);
    insert(head, p);


    pt = head;
    while(pt)
    {
        printf("%d\n", pt->data);
        pt = pt->next;
    }
}



评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。