leetcode linkedlist 从头到尾打印链表

O

问题

解决方案

代码

 /*
思路: 翻转链表之后再去打印。 属于翻转类问题。

- 
- 
- - 
- - 
- 
*/

class Solution {
    
    
public:
   vector<int> printListFromTailToHead(ListNode* head) {
    
    
       
       vector<int> ans;
       ListNode* pre =NULL, *temp =NULL;
       while(head){
    
    
           temp = head->next;
           head->next =pre;
           pre = head;
           head = temp;                      
       }
       while(pre){
    
    
           ans.push_back(pre->val);
           pre = pre->next;
       }
       return ans;
   }
};


总结与反思

  1. 注意考虑边界问题。

猜你喜欢

转载自blog.csdn.net/liupeng19970119/article/details/114237407