在Java中,可以使用递归或栈来实现反向打印链表中的元素。
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class ReversePrintLinkedList {
public static void reversePrint(ListNode head) {
if (head == null) {
return;
}
reversePrint(head.next);
System.out.println(head.val);
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
reversePrint(head);
}
}
import java.util.Stack;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class ReversePrintLinkedList {
public static void reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
ListNode current = head;
while (current != null) {
stack.push(current.val);
current = current.next;
}
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
reversePrint(head);
}
}
以上两种方法都可以实现反向打印链表中的元素。在实际应用中,可以根据具体情况选择使用哪种方法。
领取专属 10元无门槛券
手把手带您无忧上云