从尾到头打印链表
题目:输入一个链表,从尾到头打印链表每个节点的值
思路:1.递归实现(递归在本质上就是一个栈结构)
2.vector + stack,遍历链表将元素放入栈中,当遍历完整个链表后,再从栈顶开始逐个取出节点的值,放入vector容器中。
注意:头节点需要先开辟出空间,不可以直接赋空
思路1
typedef struct Node { int nCount; Node* pNext; }List; void Print_Reverse(List* pHead) { if(pHead == NULL || pHead->pNext == NULL) return; pHead = pHead->pNext; Print(pHead); cout<<pHead->nCount<<" "; } int main() { int n,num; List* pHead = (List*)malloc(sizeof(List)); pHead->pNext = NULL; cin>>n; List* pTail = pHead; while(n--) { List* p = (List*)malloc(sizeof(List)); cin>>num; p->nCount = num; p->pNext = NULL; pTail->pNext = p; pTail = p; } Print_Reverse(pHead); }
思路2
vector<int> printListFromTailToHead(ListNode* head) { stack<struct ListNode*> s; vector<int> arr; struct ListNode* pHead = head; while(pHead != NULL) { s.push(pHead); pHead = pHead->next; } while(!s.empty()) { pHead = s.top(); arr.push_back(pHead->val); s.pop(); } return arr; }