package com.zmz.algorithm.listnode;
import java.util.Arrays;
/**
* @author 张明泽
* Create by 2022/5/28 14:32
* 从尾到头打印链表
* LeetCode-剑指Offer06
*/
public class ReverseListNode {
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
head.next = node2;
node2.next = node3;
node3.next = node4;
int[] result = reverse(head);
System.out.println(Arrays.toString(result));
}
public static int[] reverse(ListNode listNode) {
ListNode cur = listNode;
int size = 0;
while (cur != null) {
size++;
cur = cur.next;
}
int[] result = new int[size];
cur = listNode;
for (int i = size - 1; i >= 0 ; i--) {
result[i] = cur.val;
cur = cur.next;
}
return result;
}
public static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static void traverse(ListNode listNode) {
while (listNode != null) {
System.out.println(listNode.val);
listNode = listNode.next;
}
}
}
最后修改:2022 年 05 月 29 日 10 : 19 PM
© 允许规范转载