{面试题5: 从尾到头打印链表}
From 剑指Offer 何海涛 著
#include <iostream> #include <stack> struct ListNode { int m_nValue; ListNode *m_pNext; }; void printListRecursively(const ListNode *pHead) { const ListNode *curr = pHead; if(pHead != NULL) { printListRecursively(curr->m_pNext); std::cout << "-> " << curr->m_nValue; } } void printListIteratively(const ListNode *pHead) { std::stack<const ListNode*> stack; const ListNode *curr = pHead; while(curr != NULL) { stack.push(curr); curr = curr->m_pNext; } while(!stack.empty()) { curr = stack.top(); std::cout << "-> " << curr->m_nValue; stack.pop(); } }
测试集:
void AddToTail(ListNode **head, int value) { if(head != NULL) { ListNode **curr = head; while(*curr != NULL) { curr = &(*curr)->m_pNext; } *curr = new ListNode; (*curr)->m_nValue = value; (*curr)->m_pNext = NULL; } } void RemoveAllNodes(ListNode **head) { if(head != NULL) { ListNode *curr = *head; while(curr != NULL) { ListNode *toBeDeleted = curr; curr = curr->m_pNext; delete toBeDeleted; } *head = NULL; } } int main(int argc, char* argv[]) { ListNode *head = NULL; AddToTail(&head, 1); AddToTail(&head, 2); AddToTail(&head, 3); AddToTail(&head, 4); AddToTail(&head, 5); printListRecursively(head); std::cout << std::endl; printListIteratively(head); RemoveAllNodes(&head); return 0; }
总结:
虽然基于递归的代码看起来很简洁, 但有个问题: 当链表非常长时, 就会导致函数调用的层级很深, 从而可能导致函数调用栈溢出。显示用栈基于循环实现的代码的鲁棒性要好一些。