从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
ListNode countNode = head;
int len = 0;
while(countNode!=null){
len++;
countNode = countNode.next;
}
countNode = head;
int res[] = new int[len];
for(int i = len-1;i>=0;i--){
res[i]=countNode.val;
countNode = countNode.next;
}
return res;
}
}
先通过第一个while获取链表长度,之通过for循环将数组从后往前修改值。
python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reversePrint(self, head):
res=[]
result=[]
while head:
res.append(head.val)
head=head.next
while res:
result.append(res.pop())
return result
先遍历链表插入数组,之后再挨个出栈保存到结果中。