-
题目描述:
-
输入一个链表,从尾到头打印链表每个节点的值。
-
输入:
-
每个输入文件仅包含一组测试样例。
每一组测试案例包含多行,每行一个大于0的整数,代表一个链表的节点。第一行是链表第一个节点的值,依次类推。当输入到-1时代表链表输入完毕。-1本身不属于链表。
-
输出:
-
对应每个测试案例,以从尾到头的顺序输出链表每个节点的值,每个值占一行。
-
样例输入:
-
1 2 3 4 5 -1
-
样例输出:
-
5 4 3 2 1
//
// main.c
// 从尾到头打印链表
//
// Created by 李亚坤 on 14-9-29.
// Copyright (c) 2014年 李亚坤. All rights reserved.
//
#include <stdio.h>
typedef struct ListElmt_ //链表元素声明
{
void *data;
struct ListElmt_ *next;
}ListElmt;
typedef struct List_ //链表声明
{
ListElmt *head;
ListElmt *tail;
int size;
}List;
void InitList(List *list) //初始化链表
{
list->size = 0;
list->head = NULL;
list->tail = NULL;
return;
}
int Insert_next(List *list, ListElmt *element, void *data) // 在element元素后面插入
{
ListElmt *new_element;
new_element = (ListElmt *)malloc(sizeof(ListElmt));
if (new_element == NULL) {
return -1;
}
new_element->data = data;
new_element->next = NULL;
if (element == NULL) {
if (list->size == 0) {
list->tail = new_element;
}
else
{
new_element->next = list->head;
}
list->head = new_element;
}
else
{
if (element->next == NULL) {
list->tail = new_element;
}
new_element->next = element->next;
element->next = new_element;
}
list->size++;
return 0;
}
void print_list_int(List *list) // 输出链表每一个元素
{
if (list->size == 0) {
return;
}
ListElmt *element;
for (element = list->head; element != list->tail; element = element->next) {
printf("%d\n", *((int *)(element->data)));
}
printf("%d\n", *((int *)(element->data)));
return;
}
int main(int argc, const char * argv[]) {
int *input, i;
input = (int *)malloc(sizeof(int));
List * l;
l = (List *)malloc((sizeof(List)));
InitList(l);
do{
scanf("%d", &input[i]);
input = (int *)realloc(input, sizeof(int) * (i+1));
if (input[i] > 0) { // 存入正整数
Insert_next(l, NULL, &input[i]);
}
i++;
}while (input[i-1] != -1);
print_list_int(l);
return 0;
}