想知道我这个代码执行output之后为什么不会输出所有节点的数据?

软件:dev c++

方法:每次选择1后,输入学生学号信息,并输出已写入学号信息的所有学生的学号信息。

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define New_node (stu*)malloc(sizeof(stu))
typedef struct student
{
	int Student_ID;
	struct student *next;

}stu;
void input(stu*R) //输入学生信息 
{
	stu *p=New_node; //p作为新节点存放p的数据 
	printf("\n请输入十位数的学号:\n");
	scanf("%d",&p->Student_ID);
	p->next=NULL;
	R->next=p;
	R=p;
}
void output(stu *L)
{
	stu *p;
	p=L->next;
	while(p!=NULL)
	{
		printf("%d\n",p->Student_ID);
		p=p->next;
	}
	
}
main()
{
	stu *L=New_node;   
	L->next=NULL;     //建立头节点
	stu *R=L;         //尾指针指向头节点 
	while(1)
	{
		int i;
		printf("请输入选择\n"); 
		scanf("%d",&i);
		switch(i)
		{
			case 1:input(R);
		    case 2:output(L);
		}
		
	}
	
}

 

你的插入方式有问题,下面是我给你改好的代码:

void input(stu*R) //输入学生信息 
{
	stu *p = New_node; //p作为新节点存放p的数据 
	printf("\n请输入十位数的学号:\n");
	scanf_s("%d", &p->Student_ID);

	while (R->next) R = R->next;	// 找到最后一个节点

	p->next = NULL;
	R->next = p;
	//R = p;
}

题主你的switch后面最好接个break,这样写别人会说你不严谨。你这个是尾插法建立链表,同时含有头指针和尾指针。注意尾指针作为实参的方式, 这里应该用尾指针的地址作为实参

我把题主的注释去了,我写了注释的地方就是我改了的地方!

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define New_node (stu*)malloc(sizeof(stu))
typedef struct student
{
    int Student_ID;
    struct student *next;
 
}stu;
void input(stu**R) //这里用二层指针修改R的值 
{
    stu *p=New_node; 
    printf("\n请输入十位数的学号:\n");
    scanf("%d",&p->Student_ID);
    p->next=NULL;
    (*R)->next=p;//*R 就是 R的实际值 
    *R=p;//修改 
}
void output(stu *L)
{
    stu *p;
    p=L->next;
    while(p!=NULL)
    {
        printf("%d\n",p->Student_ID);
        p=p->next;
    }
    
}
main()
{
    stu *L=New_node;   
    L->next=NULL;     
    stu *R=L;         
    while(1)
    {
        int i;
        printf("请输入选择\n"); 
        scanf("%d",&i);
        switch(i)
        {
            case 1:input(&R);break;//这里传地址 
            case 2:output(L);break;
        }
        
    }    
}

厉害的厉害的,我也记得翁恺讲课的时候好像有讲过这个问题。