首页 > 其他 > 详细

剑指offer:从尾到头打印链表

时间:2014-04-13 09:14:53      阅读:445      评论:0      收藏:0      [点我收藏+]

题目:输入一个链表的头结点,从尾到头反过来打印出每个节点的值。

这道题目显而易见,就是使用栈的结构,而递归又是栈的一种体现,所以是使用栈来实现本道题目。

下面是源代码:

#include<stdio.h>
typedef struct ListNode
{
    int key;
    struct ListNode *next;
}ListNode;


ListNode *insertList(ListNode *head,int value); //创建一个单链表和向一个链表中插入元素,这里默认的是头插入法
int ListLength(ListNode *head); //计算单链表的长度,不算head节点

ListNode *insertList(ListNode *head,int value)
{
    if(head->next==NULL)
    {
        ListNode *node=(ListNode *)malloc(sizeof(ListNode));
        node->key=value;
        node->next=head->next;
        head->next=node;
        node->next=NULL;
        return head;
    }
    ListNode *node=(ListNode *)malloc(sizeof(ListNode));
    node->next=head->next;
    head->next=node;
    node->key=value;
    return head;
}

int ListLength(ListNode *head)
{
    if(head->next==NULL)return 0;
    ListNode *node=head;
    int count=0;
    while(node->next!=NULL)
    {
        count++;
        node=node->next;
    }
    return count;
}

void printReverse(ListNode *head)
{
    if(head==NULL)
        return;
    printReverse(head->next);
    printf("%d\t",head->key);
}

int main()
{
    printf("请输入你要输入的数据元素的个数:\n");
    int length;
    scanf("%d",&length);
    int a[length],i;
    ListNode *head=NULL;
    head=(ListNode *)malloc(sizeof(ListNode));
    head->next=NULL;
    printf("请分别输入每个元素:\n");
    for(i=0;i<length;++i)
    {
        scanf("%d",&a[i]);
        head=insertList(head,a[i]);
    }

    printf("正序输出链表:\n");
    ListNode *node=head->next;
    while(node!=NULL)
    {
        printf("%d\t",node->key);
        node=node->next;
    }
    printf("\n反序输出链表:\n");
    printReverse(head->next);
    return 0;
}

使用递归,代码的结构十分清晰。

剑指offer:从尾到头打印链表,布布扣,bubuko.com

剑指offer:从尾到头打印链表

原文:http://blog.csdn.net/litianpenghaha/article/details/23538369

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!