标题:刚学链表...求教问题...
只看楼主
w20
Rank: 1
等 级:新手上路
帖 子:6
专家分:0
注 册:2007-8-15
 问题点数:0 回复次数:0 
刚学链表...求教问题...
下面是一个合并2个链表的程序
其中merge函数是不是有问题啊?
该怎么改啊?



#include <stdio.h>
#include <stdlib.h>
#define LINK struct link

LINK
{
    int data;
    LINK *next;
};

LINK *createLinkA(void)
{
    int i = 1;
    LINK *head = NULL,*p,*pr;
   
    while (i < 6)
    {
        p = (LINK *)malloc(sizeof(LINK));
        if(p==NULL)
            exit(0);
        p->data = i*10;
        i++;
        if(i == 2)
            head = p;
        else
            pr->next = p;
        pr = p;
    }
    p->next = NULL;

    return (head);
}

LINK *creatLinkB(void)
{
    int i = 1;
    LINK *head = NULL,*p,*pr;
   
    while (i < 6)
    {
        p = (LINK *)malloc(sizeof(LINK));
        if(p==NULL)
            exit(0);
        p->data = i*10+5;
        i++;
        if(i == 2)
            head = p;
        else
            pr->next = p;
        pr = p;
    }
    p->next = NULL;
   
    return (head);
}

void printLink(LINK *head)
{
    int i = 0;
    LINK *p;

    p = head;
    if(head == NULL)
        printf("Link is empty!\n");
    else
    {
        while (p != NULL)
        {
            printf("%10d%10d\n",i++,p->data);
            p = p->next;
        }
    }
}

LINK *merge(LINK *A,LINK *B)
{
    LINK *head = NULL,*p;

    head= A;
    p = head;
    while (B != NULL)
    {
        while (A!=NULL&&((A->data)<(B->data)))
        {
            p = A;
            A = A->next;
            p = p->next;
            p->next = NULL;
        }
        p = B;
        B = B->next;
        p = p->next;
        p->next = NULL;
    }
    return head;
}


int main()
{
    LINK *A,*B;
    LINK *head = NULL;

    A = createLinkA();
    B = creatLinkB();

    printf("The nodes of link A are:\n");
    printLink(A);
    printf("The nodes of link B are:\n");
    printLink(B);

    head=merge(A,B);
    printLink(head);

    system("pause");

    return 0;
}
搜索更多相关主题的帖子: 链表 LINK int head 
2008-05-04 20:44



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-212361-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.542824 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved