反转链表
输入一个链表,从尾到头打印链表每个节点的值。
1 #include <iostream> 2 #include <vector> 3 #include <stack> 4 5 using namespace std; 6 7 struct ListNode{ 8 ListNode(int x) : val(x), next(NULL) {} 9 int val; 10 struct ListNode* next; 11 }; 12 13 class Solution { 14 public: 15 vector<int> printListFromTailToHead(ListNode* head) 16 { 17 vector<int> vec ; 18 stack<int> sta; 19 ListNode* p = head; 20 while (p != NULL){ 21 sta.push(p->val); 22 p = p->next; 23 } 24 int length = sta.size(); 25 for (int i = 0; i < length; ++i){ 26 vec.push_back(sta.top()); 27 sta.pop(); 28 } 29 return vec; 30 } 31 32 void createList(ListNode* pHead, vector<int>& vec) 33 { 34 ListNode* p = pHead; 35 vector<int>::iterator iter = vec.begin(); 36 for (; iter != vec.end(); ++iter) 37 { 38 ListNode* pNewNode = new ListNode(*iter); 39 p->next = pNewNode; 40 p = pNewNode; 41 } 42 } 43 44 }; 45 46 int main() 47 { 48 int number; 49 cout << "Please input number:"; 50 cin >> number; 51 vector<int> vec ; 52 cout << "Please input node val:"; 53 for (int i = 0; i < number; ++i) 54 { 55 int nodeVal; 56 cin >> nodeVal; 57 vec.push_back(nodeVal); 58 } 59 60 ListNode* head = new ListNode(0); 61 Solution* pSolution = new Solution(); 62 pSolution->createList(head, vec); 63 vector<int> result ; 64 result = pSolution->printListFromTailToHead(head); 65 for (auto& i : result) 66 { 67 cout << i << endl; 68 } 69 system("pause"); 70 return 0; 71 }
方法一:链表从尾到头输出,利用递归实现,不使用库函数直接printf输出的时候用递归比较好
1 链接:https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035 2 来源:牛客网 3 4 /** 5 * struct ListNode { 6 * int val; 7 * struct ListNode *next; 8 * ListNode(int x) : 9 * val(x), next(NULL) { 10 * } 11 * }; 12 */ 13 class Solution { 14 public: 15 vector<int> printListFromTailToHead(struct ListNode* head) { 16 vector<int> value; 17 if(head != NULL) 18 { 19 value.insert(value.begin(),head->val); 20 if(head->next != NULL) 21 { 22 vector<int> tempVec = printListFromTailToHead(head->next); 23 if(tempVec.size()>0) 24 value.insert(value.begin(),tempVec.begin(),tempVec.end()); 25 } 26 27 } 28 return value; 29 } 30 };
---恢复内容结束---