搜索
楼主: 啊哈磊
打印 上一主题 下一主题

《啊哈!算法》一本开开心心的、你一定能看懂的算法书!

  [复制链接]
楼主
发表于 2014-8-15 18:10:15 | 显示全部楼层
关于啊哈算法p52页的程序,我想插入一个比链表中的数都大的数,但程序陷入死循环,求纠错!程序代码如下,求各位指点哈!
#include <stdio.h>
#include <stdlib.h>
struct node{
    int data;
    struct node *next;
};

int main()
{
    struct node *head,*p,*q,*t;
    int i,n,a;
    scanf("%d",&n);
    head=NULL;
    for(i=1;i<=n;i++){
        scanf("%d",&a);
        p=(struct node *)malloc(sizeof(struct node));
        p->data=a;
        p->next=NULL;
        if(head==NULL){
            head=p;
            q=p;
        }
        else
            q->next=p;
        q=p;
    }
    printf("linklist as bellow:\n");
    t=head;
    while(t!=NULL){
        printf("%d ",t->data);
        t=t->next;
    }
    printf("\ninput number which you want to insert:");
    scanf("%d",&a);
    t=head;
    while(t->next!=NULL){
        if(t->next->data > a){
             p=(struct node *)malloc(sizeof(struct node));
             p->data=a;
             p->next=t->next;
             t->next=p;
             break;
        }
        t=t->next;
    }
    if(t->next==NULL){
        p=(struct node *)malloc(sizeof(struct node));
        p->data=a;
        t->next=p;
        t=p;
    }
    t=head;
    while(t!=NULL){
        printf("%d ",t->data);
        t=t->next;
    }
    getchar();getchar();
    return 0;
}
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

广播台
特别关注
快速回复 返回顶部 返回列表