剑指 Offer 06 从尾到头打印链表
1 题目
- 输入一个链表的头节点,从尾到头反过来打印出每个节点的值。
2 提示
3 示例
输入: [1,2,3,4,5]
输出: [5,4,3,2,1]
输入: [1,2]
输出: [2,1]
输入: []
输出: []
4 解题思路
5 复杂度分析
6 题解
public class JZ06_从尾到头打印链表 {
public static void main(String[] args) {
ListNode head = ListNode.createListNode(new int[]{1, 2, 3, 4, 5});
PrintUtils.getInstance().printListNode(solution(head));
}
private static ListNode solution(ListNode head) {
if (head == null || head.next == null) return head;
ListNode pre = null, curr = head, next = null;
while (curr != null) {
next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}
}