鱼C论坛

 找回密码
 立即注册
查看: 1459|回复: 0

[技术交流] C++刷剑指offer(面试题06. 从尾到头打印链表)【链表】

[复制链接]
发表于 2020-3-28 20:28:22 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 糖逗 于 2020-5-8 18:02 编辑

题目描述:
  1. 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

  2.  

  3. 示例 1:

  4. 输入:head = [1,3,2]
  5. 输出:[2,3,1]
  6.  

  7. 限制:

  8. 0 <= 链表长度 <= 10000

  9. 来源:力扣(LeetCode)
  10. 链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
  11. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码


  1. #include <stack>
  2. #include <iostream>
  3. #include <vector>
  4. using namespace std;

  5. struct ListNode{
  6.         int value;
  7.         ListNode *next;
  8.         ListNode(int x) : value(x), next(NULL) {}
  9. };



  10. void printList(ListNode* head){
  11.         ListNode* temp = head;
  12.         while(temp -> next != NULL){
  13.                 temp = temp -> next;
  14.                 cout << temp -> value << " ";
  15.         }
  16.         cout << endl;
  17. }


  18. vector<int> solution(ListNode* head){
  19.         vector<int> result;
  20.         stack<int> out;
  21.         ListNode* temp = head -> next;
  22.         while(temp -> next != NULL){
  23.                 out.push(temp -> value);
  24.                 temp = temp -> next;
  25.         }
  26.         out.push(temp -> value);
  27.         while(!out.empty()){
  28.                 result.push_back(out.top());
  29.                 out.pop();
  30.         }
  31.         return result;
  32. }

  33. int main(void){
  34.         int number;
  35.         ListNode* head = new ListNode(0);
  36.         ListNode* temp = head;
  37.         while(cin >> number){
  38.                 ListNode* node = new ListNode(number);
  39.                 temp -> next = node;
  40.                 temp = node;               
  41.         }
  42.         cout << "finish!" << endl;
  43.         printList(head);
  44.         vector<int> result = solution(head);
  45.         for(int i = 0; i < result.size(); i++){
  46.                 cout << result[i] << " ";
  47.         }
  48.         cout << endl;
  49.        
  50.         return 0;
  51. }
复制代码


参考链接:http://www.manongjc.com/article/61445.html

注意事项:
1.这里自己定义了一个head为0。
2.要定义一个temp指针=head,防止后续head指针变换。
3.单链表中各元素地址是不连续的,所以这里用了一个new生成新node。

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-5 20:50

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表