| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 447 人关注过本帖
标题:在链表插入中,当插入位置i=1时为何程序运行的结果不像是插入的数据,求指教 ...
只看楼主 加入收藏
初学者_12
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2012-8-4
收藏
 问题点数:0 回复次数:2 
在链表插入中,当插入位置i=1时为何程序运行的结果不像是插入的数据,求指教,谢谢
代码如下:
#include "stdio.h"
#include "stdlib.h"
struct node
{
    int NO;
    int score;
    struct node *next;
};
struct node *creat()
{
    struct node *p,*listp,*listhead;
    int i;
    for(i=1;i<4;i++)
    {
        p=(struct node *)malloc(sizeof(struct node));
        if(i==1)
        listhead=p;
        else
        listp->next=p;
        listp=p;
        listp->next=NULL;
        printf("请输入第%d个同学的学号和成绩:",i);
        scanf("%d %d",&p->NO,&p->score);
    }
    return listhead;
}
void print(struct node *listhead)
{
    struct node *p;
    if(listhead==NULL)
    {
        printf("链表为空");
        return ;
    }
    p=listhead;
    while(p!=NULL)
    {
    printf("%d %d\n",p->NO,p->score);
    p=p->next;
    }
}
struct node *insert(struct node *listhead)
{
    struct node *p,*listp;
    int i,x,y;
    printf("请输入要插入的位置和数据:");
    scanf("%d %d %d",&i,&x,&y);
    if(listhead==NULL)
    {
        printf("链表还没有建立!\n");
        return listhead;
    }
    int k=1;
    listp=listhead;
    while(listp!=NULL&&k<i-1)
    {
        listp=listp->next;
        k++;
    }
    if(k<i-1||i<1)
    printf("插入位置必须大于零小于%d\n",k+1);
    else if(i==1)
    {
    if((p=(struct node *)malloc(sizeof(struct node)))==NULL)
    {
        printf("内存分配错误!\n");
        exit(0);
    }
    p->NO=x;
    p->score=y;
    p->next=listhead;
    listhead=p;
    }
    else
    {
        if((p=(struct node *)malloc(sizeof(struct node)))==NULL)
        {
            printf("内存分配错误!\n");
            exit(0);
        }
        p->NO=x;
        p->score=y;
        p->next=listp->next;
        listp->next=p;
    }
    return listhead;
}
int main()
{
    struct node *listhead;
    listhead=creat();
    insert(listhead);
    print(listhead);
}
搜索更多相关主题的帖子: next include return 
2012-08-04 10:29
hao02171990
Rank: 2
等 级:论坛游民
帖 子:17
专家分:17
注 册:2012-6-20
收藏
得分:0 
哦!我看了半天,没有发现错误啊!一切正常啊!无言!
2012-08-14 11:17
chuanglan
Rank: 2
等 级:论坛游民
威 望:2
帖 子:91
专家分:29
注 册:2012-8-14
收藏
得分:0 
我发现的问题比较多。。。都是些小问题,加我扣扣聊,994564686,刺客
2012-08-15 11:18
快速回复:在链表插入中,当插入位置i=1时为何程序运行的结果不像是插入的数据, ...
数据加载中...
 
   



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

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