【剑指offer】6、从尾到头打印链表

题目

输入一个链表的头节点,从尾到头反过来打印出每个节点的值。

思路1

先进后出,用栈实现

vector<int> printListFromTailToHead(ListNode* head) {
    stack<int> nodes;
    vector<int> result;
         
    while( head != nullptr)
    {
    nodes.push(head->val);
    head = head->next;
  }
  while(!nodes.empty())
  {
    result.push_back(nodes.top());
    nodes.pop();
  }
  return result; }

思路2

递归在本质上是一个栈,因此也可以用递归来解决

vector<int> printListFromTailToHead(ListNode* head) {
  vector<int> res;
  if(head == nullptr)
      return re;
  printListRec(head, res);
  return res;
}

void printListRec(ListNode* head,vector<int> &re){   if(head == nullptr)     return;   printListRec(head->next,re);   re.push_back(head->val);   return; }

或者

vector<int> printListFromTailToHead(ListNode* head) {
  vector<int> res;
  if(head == nullptr)
    return re;
  res = printListFromTailToHead(head->next);//直接在这个函数用递归
  res.push_back(head->val);
  return re;
}

思路3

用vector的反向迭代器

vector<int> printListFromTailToHead(ListNode* head) {
  vector<int> res;
  while ( head != nullptr)
  {
    res.push_back(head->val);
    head = head->next;
  }
  return vector<int>(res.rbegin(), res.rend());
}

猜你喜欢

转载自www.cnblogs.com/shiganquan/p/9281759.html