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);

}

 

posted @ 2023-05-11 09:04  放氮气的蜗牛  阅读(131)  评论(0编辑  收藏  举报  来源