从尾到头打印链表
方法1:
利用栈,先把链表中的元素,依次放入栈中,并得到多少个数值,从而定义一个数组,然后依次出栈保存到数组中。
我们熟悉一下栈中的基本方法:
- boolean empty() 测试堆栈是否为空
- Object peek( ) 查看堆栈顶部的对象,但不从堆栈中移除它。
- Object pop( ) 移除堆栈顶部的对象,并作为此函数的值返回该对象。
- Object push(Object element) 把项压入堆栈顶部。
- int size() 返回栈的大小
- int search(Object element) 返回对象在堆栈中的位置,以 1 为基数。
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
import java.util.*;
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<Integer>();
while (head != null) {
stack.push(head.val);
head = head.next;
}
int count = stack.size();
int [] res = new int [count];
int i = 0;
while (!stack.isEmpty()) {
res[i] = stack.peek();
stack.pop();
i++;
}
return res;
}
}
方法2:
这种算法不需要依靠栈
先遍历链表,求出链表的长度,从而创建等长的数组。
然后从数组最后开始记录链表的值。
代码:
/**
* 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 length = 0;
ListNode node = head;
while (node != null) {
length++;
node = node.next;
}
int [] res = new int [length];
for (int i = length - 1; i >= 0; i--) {
res[i] = head.val;
head = head.next;
}
return res;
}
}
/**
* 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 length = 0;
ListNode node = head;
while (node != null) {
length++;
node = node.next;
}
int [] res = new int [length];
for (int i = length - 1; i >= 0; i–) {
res[i] = head.val;
head = head.next;
}
return res;
}
}