题目:输入一个链表的头结点,从尾到头反过来打印出每个节点的值。
这道题目显而易见,就是使用栈的结构,而递归又是栈的一种体现,所以是使用栈来实现本道题目。
下面是源代码:
#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
原文:http://blog.csdn.net/litianpenghaha/article/details/23538369