1278 - C语言11.14
建立一个链表,每个节点包括一个学号信息。将这个链表按逆序排列并输出,即将链表头作为链尾,链表尾作为链头。
Input
第一行有一个整数n,表示链表中的节点个数。保证n不超过100。
之后的n行每行有1个整数,表示每个节点对应的学号信息。
Output
输出逆序排列的链表,每行一个整数表示节点的学号信息。
请注意行尾输出换行。
Examples
Input
5 101 103 105 102 104
Output
104 102 105 103 101
Solution C
#include <stdio.h> int main() { int n,k,j,a[100]; scanf("%d",&n); for (k=0;k<n;k++) scanf("%d",&a[k]); for (j=n-1;j>=0;j--) printf ("%d\n",a[j]); return 0; }
Solution C++
#include <stdio.h> #include <stdlib.h> struct node { int num; struct node * next; }; int main() { struct node *head, *tail, *newhead, *p, *pa; int n, i; scanf("%d", &n); /* 读入a链表中的n个人的信息 */ head = tail = NULL; for (i = 0;i < n;i++) { p = (struct node *)malloc(sizeof(struct node)); scanf("%d", &p->num); if (head == NULL) { head = tail = p; } else { tail->next = p; tail = p; } } tail->next = NULL; /* 遍历链表的每一个节点,将其添加到新的逆序链表的最前端 */ newhead = NULL; p = head; while (p != NULL) { pa = p->next; if (newhead == NULL) p->next = NULL; else p->next = newhead; newhead = p; p = pa; } /* 将处理后的链表进行输出 */ p = newhead; while (p != NULL) { printf("%d\n", p->num); p = p->next; } return 0; }