面试题6:从尾到头打印链表

一、题目

     输入一个链表的头结点,从尾到头反过来打印每个节点的值,链表定义如下:

struct ListNode()
{
    int value;
    ListNode* next
}

二、解法

    分析:看到该题第一反应是从头到尾输出将会比较简单,于是自然的想到把链表中的链接节点的指针翻转过来,改变链表的方向,然后就可以从头到尾的输出了,但是该方法会改变原链表的结构。

2.1 方法一(栈)

    解决这个问题肯定要遍历链表,链表的顺序是从头到尾,可输出顺序是从尾到头,这是典型的“后进先出”,可以用栈实现这种顺序,当遍历完整个链表,再从栈顶开始逐个输出节点的值,此时输出的节点的顺序已经翻转过来了,这种思路的实现代码如下:

void PrintListReversingly_Iteratively(ListNode* pHead)
{
    std::stack<ListNode*> nodes;

    ListNode* pNode = pHead;
    while(pNode != nullptr)
    {
        nodes.push(pNode);
        pNode = pNode->m_pNext;
    }

    while(!nodes.empty())
    {
        pNode = nodes.top();
        printf("%d\t", pNode->m_nValue);
        nodes.pop();
    }
}
2.2 方法二(递归)

    既然想到了用栈实现这个函数,而递归在本质上就是一个栈结构,于是自然的又想到了使用递归来实现,要想实现反过来输出链表,我们每访问到一个节点的时候,先递归输出它后面的节点,再输出该节点自身,这样链表的输出结果就反过来了。

void PrintListReversingly_Recursively(ListNode* pHead)
{
    if(pHead != nullptr)
    {
        if (pHead->m_pNext != nullptr)
        {
            PrintListReversingly_Recursively(pHead->m_pNext);
        }
 
        printf("%d\t", pHead->m_nValue);
    }
}
基于递归的代码看起来很简洁,但是有一个问题:当链表非常长的时候,就会导致函数调用的层级很深,从而有可能导致函数调用栈溢出。显然用栈基于循环实现的代码的鲁棒性更好一些。

三、代码测试

1. 创建节点
ListNode* CreateListNode(int value)
{
    ListNode* pNode = new ListNode();
    pNode->m_nValue = value;
    pNode->m_pNext = nullptr;

    return pNode;
}

2. 链接节点

void ConnectListNodes(ListNode* pCurrent, ListNode* pNext)
{
    if(pCurrent == nullptr)
    {
        printf("Error to connect two nodes.\n");
        exit(1);
    }

    pCurrent->m_pNext = pNext;
}

3. 主函数测试

int main(int argc, char* argv[])
{ ListNode* pNode1 = CreateListNode(1); ListNode* pNode2 = CreateListNode(2); ListNode* pNode3 = CreateListNode(3); ListNode* pNode4 = CreateListNode(4); ListNode* pNode5 = CreateListNode(5); ConnectListNodes(pNode1, pNode2); ConnectListNodes(pNode2, pNode3); ConnectListNodes(pNode3, pNode4); ConnectListNodes(pNode4, pNode5); PrintListReversingly_Iteratively(pHead); printf("\n"); PrintListReversingly_Recursively(pHead); return 0;}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值