剑指offer之从尾到头打印链表(C++/Java双重实现)

1.题目描述

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000

在这里插入图片描述

2.问题分析:

C++的话使用vector容器就行,使用里边的函数就行
Java我们可以使用两次遍历,第一次遍历记录结点的数目,然后第二次遍历把数据从末尾到头依次传递给数组

3.代码实现:

3.1C++代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> ans;
        while(head != NULL) {
            ans.push_back(head->val);
            head = head->next;
        }
        reverse(ans.begin(),ans.end());//反转容器
        return ans;
    }
};
3.2Java代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        int cnt=0;
        ListNode cur=head;
        while(cur!=null)
        {
            cur=cur.next;
            cnt++;
        }
        cur=head;
        int arr[]=new int[cnt];
        while(cur!=null)
        {
            arr[--cnt]=cur.val;
            cur=cur.next;
        }
        return arr;

    }
}

猜你喜欢

转载自blog.csdn.net/qq_45737068/article/details/107113474