think: 1顺序插入元素建立顺序链表+链表的逆置+链表的顺序输出
sdut原题链接
数据结构实验之链表三:链表的逆置 Time Limit: 1000MS Memory Limit: 65536KB
Problem Description 输入多个整数,以-1作为结束标志,顺序建立一个带头结点的单链表,之后对该单链表的数据进行逆置,并输出逆置后的单链表数据。
Input 输入多个整数,以-1作为结束标志。
Output 输出逆置后的单链表数据。
Example Input 12 56 4 6 55 15 33 62 -1
Example Output 62 33 15 55 6 4 56 12
Hint 不得使用数组。
Author
以下为accepted代码
#include <stdio.h> #include <stdlib.h> struct node { int Data; struct node *next; }*head, *tail; void Insert(int x);//顺序插入元素建立顺序链表 void Build(struct node *h);//链表内的元素的逆置 void Pri(struct node *h);//链表内元素的输出 int main() { int x; head = (struct node *)malloc(sizeof(struct node)); head->next = NULL; tail = head; while(scanf("%d", &x) && x != -1) { Insert(x);//顺序插入元素建立顺序链表 } Build(head);//链表内元素的逆置 Pri(head);//链表内元素的输出 return 0; } void Insert(int x)//顺序插入元素建立顺序链表 { struct node *p; p = (struct node *)malloc(sizeof(struct node)); p->Data = x; p->next = tail->next; tail->next = p; tail = p; } void Pri(struct node *h)//链表内元素的输出 { struct node *p; p = h->next; while(p != NULL) { printf("%d%c", p->Data, p->next == NULL? '\n': ' '); p = p->next; } } void Build(struct node *h)//链表内元素的逆置 { struct node *p, *q; p = h->next; if(p->next != NULL) { q = p->next; h->next = NULL; while(q != NULL) { p->next = h->next; h->next = p; p = q; q = q->next; } p->next = h->next; h->next = p; } } /*************************************************** User name: Result: Accepted Take time: 0ms Take Memory: 108KB Submit time: 2017-03-09 16:03:07 ****************************************************/