C语言输入若干个正整数(输入-1为结束标志),要求按输入数据的逆序建立单链表并输出。
/*
开发者:慢蜗牛 开发时间:2020.6.11
程序功能:逆序建立链表,顺序输出
*/
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct once)
struct once//建立结构
{
int a;
struct once* next;
};
struct once* out()//建立头插法逆序建立链表
{
int n = 0;
struct once* p1, * p2;
printf("请输入:");
p1 = p2 = (struct once*)malloc(LEN);
scanf_s("%d", &p1->a);
p2->next = NULL;
while (p1->a != -1)
{
if (n == 0) p1->next = p2->next;
else p1->next = p2;
p2 = p1;
p1 = (struct once*)malloc(LEN);
scanf_s("%d", &p1->a);
n = n + 1;
}
return(p2);
}
void print(struct once* head)//输出链表
{
struct once* p1, * p2, * p3, * p;
p3 = p1 = p2 = (struct once*)malloc(LEN);
p1->next = head; head = p1;
p1 = head->next;
do//反转
{
p3 = head->next; p2 = p1->next;
head->next = p2; p1->next = p2->next;
p2->next = p3;
} while (p1->next != NULL);
p = head->next;
do//输出头节点链表
{
printf("--%d", p->a);
p = p->next;
} while (p != NULL);
}
void main()//调用函数
{
struct once* head;
head = out();
print(head);
}