广元做网站长沙网站优化公司
数据结构实验之链表二:逆序建立链表
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic
Problem Description
输入整数个数N,再输入N个整数,按照这些整数输入的相反顺序建立单链表,并依次遍历输出单链表的数据。
Input
第一行输入整数N;;
第二行依次输入N个整数,逆序建立单链表。
Output
依次输出单链表所存放的数据。
Sample Input
10 11 3 5 27 9 12 43 16 84 22
Sample Output
22 84 16 43 12 9 27 5 3 11
Hint
不能使用数组!
#include <stdio.h>
#include <stdlib.h>
struct node
{int data;///数据域struct node * next;///指针域
};
struct node * reverse_creat(int);///创建逆序链表函数
void output(struct node *);///输出链表函数,需要输入链表头结点的地址
int main()
{int N;struct node * head;scanf("%d", &N);head = reverse_creat(N);///创建链表并返回链表头结点地址output(head);///输出链表,传入链表头结点地址return 0;
}
struct node * reverse_creat(int n)
{struct node *head, *p;int i;head = (struct node *)malloc(sizeof(struct node));head->next = NULL;///为头结点分配地址,并使其指针域指向空for(i = 1; i <= n; i++){p = (struct node *)malloc(sizeof(struct node));///为新结点分配内存空间scanf("%d", &p->data);///读入数据,存储在p的数据域p->next = head->next;///让新节点的指针域指向原来头结点的后面的结点head->next = p;///让头结点的指针域(next)指向新结点p}return head;///返回链表的头结点地址
};
void output(struct node *head)
{struct node * p;p = head->next;///让 p 指向第一个结点,不是 head!!!while(p != NULL){///当 p 为空时结束循环if(p == head->next) printf("%d", p->data);///如果 p 指向的是第一个结点,则不输出空格else printf(" %d", p->data);p = p->next;///输出完一个结点后让 p 指向下一个结点}printf("\n");
}