【leetcode】【剑指 Offer 06】【从尾到头打印链表】

c++

第一个方法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    size_t length(ListNode* head){
        if( nullptr == head ){
            return 0;
        }
        size_t len = 0;
        auto cursor = head;
        while( nullptr != cursor){
            len++;
            cursor = cursor->next;
        }
        return len;
    }
    vector<int> reversePrint(ListNode* head) {
        auto len = length(head);
        vector<int> ret(len);
        if( nullptr == head ){
            return ret;
        }
        auto cursor = head;
        auto index = len - 1;
        while( nullptr != cursor ){
            ret[index--] = cursor->val;
            cursor = cursor->next;
        }

        return ret;
    }
};

java

第一个方法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int length(ListNode head){
        if( null == head ){
            return 0;
        }
        int len = 0;
        ListNode cursor = head;
        while( null != cursor){
            len++;
            cursor = cursor.next;
        }
        return len;
    }
    public int[] reversePrint(ListNode head) {
        int len = length(head);
        int[] ret = new int[len];
        if( null == head ){
            return ret;
        }

        int index = len - 1;
        ListNode cursor = head;
        while( null != cursor ){
            ret[index--] = cursor.val;
            cursor = cursor.next;
        }
        return ret;
    }
}
posted @ 2023-07-04 09:45  laolang2016  阅读(3)  评论(0编辑  收藏  举报