题目:
输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
链表结点定义如下:
struct ListNode{int m_nKey;ListNode* m_pNext;
};
解答:
这题做出来不难,但是要以最短的时间和最优的空间却很难。
这题要反向输出,可以用栈来实现,但是用栈的话,需要O(n)的空间复杂度。
书中提供了一种非常好的思路(让我相当佩服),就是利用递归来实现先进后出,下面是实现。
时间复杂度:O(n)
空间复杂度:O(1)
#include <iostream>
#include <vector>
#include <string>
using namespace std;struct ListNode{int m_nKey;ListNode* m_pNext;ListNode() :m_pNext(NULL){}
};void reversePrint(ListNode* head)
{if (head == NULL) return;reversePrint(head->m_pNext);cout << head->m_nKey <<endl;
}int main()
{ListNode *a1 = new ListNode, *a2 = new ListNode, *a3 = new ListNode;a1->m_nKey = 1;a2->m_nKey = 2;a3->m_nKey = 3;a1->m_pNext = a2;a2->m_pNext = a3;a3->m_pNext = NULL;reversePrint(a1);return 0;
}