(FB) 链表的递归与倒序打印
(FB) 在不修改链表结构和数据的情况下,倒序输出链表
他妈的,写完代码之后发现我特意建一个页面总结这题的目的是什么。。
private static void reversePrintList_recursive(ListNode head){
if(head.next == null){
System.out.print(head.val + ",");
return;
}
reversePrintList_recursive(head.next);
System.out.print(head.val + ",");
}
private static void reversePrintList_iterative(ListNode head){
int size = 0;
ListNode cur = head;
while(cur != null){
size++;
cur = cur.next;
}
for(; size > 0; size --){
ListNode ptr = head;
for(int i = 0; i < size - 1; i++) ptr = ptr.next;
System.out.print(ptr.val + ",");
}
}
public static void main(String[] args) {
// 5 -> 4 -> 3 -> 2 -> 1 -> 0 -> NULL
ListNode node5 = new ListNode(5);
ListNode node4 = new ListNode(4);
ListNode node3 = new ListNode(3);
ListNode node2 = new ListNode(2);
ListNode node1 = new ListNode(1);
ListNode node0 = new ListNode(0);
node5.next = node4;
node4.next = node3;
node3.next = node2;
node2.next = node1;
node1.next = node0;
reversePrintList_recursive(node5);
reversePrintList_iterative(node5);
}