数据结构——算法之(021)( 从尾到头输出链表)
2014-05-27 11:56
477 查看
【申明:本文仅限于自我归纳总结和相互交流,有纰漏还望各位指出。 联系邮箱:Mr_chenping@163.com】
题目:
输入一个链表的头结点,从尾到头反过来输出每个结点的值。链表结点定义如下:
题目分析:
给出三种解题方法:(注意,单向链表只能顺序遍历)
(1)栈:顺序遍历链表,把每个节点入栈,最后在出栈。
(2)链表逆序:链表逆序,然后正序输出每个节点(题目没有注明不能修改表接口)
(3)递归:最简单,但最不容易想到的方法
算法实现:
题目:
输入一个链表的头结点,从尾到头反过来输出每个结点的值。链表结点定义如下:
typedef struct _list_node { int key; struct _list_node *next; }list_node;
题目分析:
给出三种解题方法:(注意,单向链表只能顺序遍历)
(1)栈:顺序遍历链表,把每个节点入栈,最后在出栈。
(2)链表逆序:链表逆序,然后正序输出每个节点(题目没有注明不能修改表接口)
(3)递归:最简单,但最不容易想到的方法
算法实现:
#include <stdio.h>
#include <stdlib.h>
typedef struct _list_node { int key; struct _list_node *next; }list_node;
void *list_insert(list_node *head, int key)
{
list_node *p = head;
while(p->next != NULL)
p = p->next;
list_node *node = calloc(1, sizeof(list_node));
node->key = key;
node->next = NULL;
p->next = node;
}
void reverse_display(list_node *head)
{
list_node *p = head->next;
if(head->next != NULL)
reverse_display(head->next);
printf(" %d", head->key);
printf("\n");
}
int main(int argc, char *argv[])
{
list_node *head = calloc(1, sizeof(list_node));
head->key = 0;
head->next = NULL;
list_insert(head, 1);
list_insert(head, 2);
list_insert(head, 3);
list_insert(head, 4);
list_insert(head, 5);
reverse_display(head);
free(head);
return 0;
}
相关文章推荐
- 数据结构——算法之(004)(输入一个单向链表,输出该链表中倒数第k个结点)
- 【数据结构与算法】第三章 栈c实现,使用链表结构
- 数据结构之链表合并算法
- 数据结构与算法 2、单向/双向链表
- 数据结构与算法-链表的基本操作---ShinPans
- 数据结构与算法学习--链表
- 算法与数据结构之三----循环链表
- 转:C#数据结构和算法学习系列十三----链表
- 数据结构基础_逆向输出链表
- .net 数据结构与算法基础:泛型链表使用
- 【数据结构与算法基础】单链表及其应用基数排序 / Singly Linked List and radix sort
- 数据结构与算法——链表
- 数据结构与算法之—链表(二) 有序单链表合并
- 数据结构实验一--单链表的基本操作的算法
- 数据结构之单链表取第i个元素的算法
- 数据结构之链表合并算法
- 数据结构之链表合并算法
- 数据结构与算法面试题汇编(1)- 链表的操作与应用
- 链表相关的算法题大汇总 — 数据结构之链表奇思妙想
- 数据结构之链表基本操作算法演示