我想写一个单链表,然后用节点内部数据排序输出、
然后就出现了这个问题。
这个是我的代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define LEN sizeof(struct Teacher)
struct Teacher
{
char name[20];
int number;
struct Teacher* next;
};
int n;
struct Teacher* creat()
{
struct Teacher* p1 = NULL;
struct Teacher* p2 = NULL;
struct Teacher *head = NULL;
p1 = p2 = new struct Teacher;
scanf_s("%s%d", p1->name, sizeof(p1->name), &p1->number);
while (p1->number != 0)
{
n = n + 1;
if (n == 1)
head = p1;
else
p2->next = p1;
p2 = p1;
p1 = new struct Teacher;
scanf_s("%s%d", p1->name, sizeof(p1->name), &p1->number);
}
p2 = NULL;
return head;
}
void print_teacher(struct Teacher* head) //输出信息列表
{
struct Teacher* p;
p = head;
if (head != NULL)
{
while (p != NULL)
{
printf("%s %d\n", p->name, p->number);
p = p->next;
}
}
}
void sort_teacher1(struct Teacher* head) //教师工号排序(升序)
{
if (head == NULL)
return ;
else
{
struct Teacher* p1 = head;
struct Teacher* p2 = NULL;
while (p1->next != NULL)
{
p2 = p1->next;
if (p1->number >p2->number)
{
Teacher t;
t = *p1;
t.next = p2->next;
p2->next = p1->next;
*p1 = *p2;
*p2 = t;
}
p1 = p1->next;
}
}
}
int main()
{
struct Teacher* head;
head = creat();
sort_teacher1(head);
print_teacher(head);
return 0;
}