题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
struct ListNode { int key; ListNode *next; }; void addToTail(ListNode **pHead, int value) { // 调用时实参指针pHead应该取引用 ListNode *temp = new ListNode; temp -> key = value; temp -> next =NULL; if (*pHead == NULL) { *pHead = temp; return; } ListNode* p = *pHead; while (p -> next != NULL) p = p -> next; p -> next = temp; } void printListReversingly(ListNode *pHead) { //用栈实现 反向便利 std:: stack<ListNode* > nodes; ListNode *p = pHead; while (p != NULL) { nodes.push(p); p = p -> next; } while (!nodes.empty()) { std::cout << nodes.top() -> key << std:: endl; nodes.pop(); } } void printListReversingRecursively(ListNode *pHead) { //递归实现 if (pHead == NULL) return; printListReversingRecursively(pHead -> next); std:: cout<< pHead -> key << std:: endl; }