【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;
}
}
本文来自博客园,作者:laolang2016,转载请注明原文链接:https://www.cnblogs.com/khlbat/p/17524862.html