面试题06. 从尾到头打印链表
题目:
解答:
方法一:栈保存,先进后出。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 vector<int> reversePrint(ListNode* head) 12 { 13 vector<int> res; 14 std::stack<int> st; 15 16 if (NULL == head) 17 { 18 return res; 19 } 20 21 while (head != NULL) 22 { 23 st.push(head->val); 24 head = head->next; 25 } 26 27 while (!st.empty()) 28 { 29 res.push_back(st.top()); 30 st.pop(); 31 } 32 33 return res; 34 } 35 };
方法二:反转链表,然后在进行遍历。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 12 ListNode * reverse(ListNode *head) 13 { 14 if (NULL == head || NULL == head->next) 15 { 16 return head; 17 } 18 19 ListNode *p1; 20 ListNode *p2; 21 ListNode *p3; 22 23 p1 = head; 24 p2 = head->next; 25 26 while (p2 != NULL) 27 { 28 p3 = p2->next; 29 p2->next = p1; 30 p1 = p2; 31 p2 = p3; 32 } 33 34 head->next = NULL; 35 head = p1; 36 37 return head; 38 } 39 40 vector<int> reversePrint(ListNode* head) 41 { 42 vector<int> res; 43 44 if (NULL == head) 45 { 46 return res; 47 } 48 49 ListNode *new_head = reverse(head); 50 51 while (new_head != NULL) 52 { 53 res.push_back(new_head->val); 54 new_head = new_head->next; 55 } 56 57 return res; 58 } 59 };
方法三:递归
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 vector<int> res; 12 vector<int> reversePrint(ListNode* head) 13 { 14 if(head == nullptr) 15 { 16 return res; 17 } 18 reversePrint(head->next); 19 res.push_back(head->val); 20 return res; 21 } 22 };