且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从尾到头打印链表

更新时间:2022-09-16 21:01:00

题目描写叙述:

输入一个链表。从尾到头打印链表每一个节点的值。

输入:

每一个输入文件仅包括一组測试例子。
每一组測试案例包括多行。每行一个大于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;
}






本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/5091487.html,如需转载请自行联系原作者