从尾到头打印链表



题目描述:

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

输入:

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值