从头到尾打印链表
2017-08-26 10:13
169 查看
题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值。链表的定义如下:
【解题思路】(递归)
先递归出后面的节点,在输出节点本身。不足:当链表比较长时,会使函数调用层级比较深而导致函数调用栈溢出。
【代码】
【程序】
运行结果:
【附加】(栈方法)
每经过一个节点的时候把节点放到一个栈中,遍历完节点后再从栈顶开始逐个输出节点的值。
【代码】
typedef int DataType; typedef struct Node { DataType data; struct Node *next; }Node, *pList, *pNode;
【解题思路】(递归)
先递归出后面的节点,在输出节点本身。不足:当链表比较长时,会使函数调用层级比较深而导致函数调用栈溢出。
【代码】
void ReversePrint(pList phead) { if (phead != NULL) { if (phead->next) { ReversePrint(phead->next); } printf("%d ", phead->data); } }
【程序】
#define _CRT_SECURE_NO_WARNINGS 1
# include <stdio.h>
# include <stdlib.h>
# include <assert.h>
typedef int DataType; typedef struct Node { DataType data; struct Node *next; }Node, *pList, *pNode;
void InitLinkList(pList *pplist)
{
assert(pplist);
*pplist = NULL;
}
void PushBack(pList *pplist, DataType x)
{
pNode cur = *pplist;
pNode pnode = NULL;
assert(pplist);
pnode = (pNode)malloc(sizeof(Node));
if (pnode == NULL)
{
perror("PushBack::malloc");
exit(EXIT_FAILURE);
}
pnode->data = x;
pnode->next = NULL;
if (cur == NULL)
{
*pplist = pnode;
}
else
{
while (cur->next != NULL)
{
cur = cur->next;
}
cur->next = pnode;
}
}
void Display(pList plist)
{
pNode cur = plist;
while (cur)
{
printf("%d-->", cur->data);
cur = cur->next;
}
printf("over\n");
}
void Destroy(pList *pplist)
{
pNode cur = *pplist;
a
4000
ssert(pplist);
while (cur)
{
pNode del = cur;
cur = cur->next;
free(del);
}
*pplist = NULL;
}
void ReversePrint(pList phead) { if (phead != NULL) { if (phead->next) { ReversePrint(phead->next); } printf("%d ", phead->data); } }
void test1()
{
pList plist;
pNode ret = NULL;
InitLinkList(&plist);
PushBack(&plist, 1);
PushBack(&plist, 2);
PushBack(&plist, 3);
PushBack(&plist, 4);
PushBack(&plist, 5);
PushBack(&plist, 6);
Display(plist);
ReversePrint(plist);
Destroy(&plist);
}
int main()
{
test1();
system("pause");
return 0;
}
运行结果:
【附加】(栈方法)
每经过一个节点的时候把节点放到一个栈中,遍历完节点后再从栈顶开始逐个输出节点的值。
【代码】
void ReversePrint(pList phead) { std::stack<pList>nodes; pNode pnode = phead; while (pnode != NULL) { nodes.push(pnode); pnode = pnode->next; } while (!nodes.empty()) { pnode = nodes.top(); printf("%d\t", pnode->data); nodes.pop(); } }
相关文章推荐
- 从头到尾打印链表,两种方法:用栈先进后出,另一种为递归。
- 剑指offer 从头到尾打印链表
- 从头到尾打印链表
- [牛客网,剑指offer,python] 从头到尾打印链表
- 剑指offer编程题——05 从头到尾打印链表
- 剑指 offer set 2 从头到尾打印链表
- 面试题5:从头到尾打印链表
- 剑指offer面试题之从头到尾打印链表
- Offer题5 链表末尾插入&删除指定值&从头到尾打印
- [牛客网,剑指offer,python] 从头到尾打印链表
- 从头到尾打印链表
- [牛客网,剑指offer,python] 从头到尾打印链表
- 从头到尾打印链表
- 算法题/从头到尾打印链表
- 剑指offer--面试题6:从头到尾打印链表
- [牛客网,剑指offer,python] 从头到尾打印链表
- 《剑指Offer》面试题-从头到尾打印链表
- 《剑指Offer》面试题-从头到尾打印链表
- 从头到尾打印链表
- 剑指offer 面试题5——从头到尾打印链表