从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)
思路:首先需要对链表进行逆序
然后再对将链表保存在数组中
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public int[] reversePrint(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode next = null;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
ListNode reverseListNode = pre;
ArrayList<Integer> list = new ArrayList<>();
while (reverseListNode != null) {
list.add(reverseListNode.val);
reverseListNode = reverseListNode.next;
}
int[] array = new int[list.size()];
for(int i=0;i<list.size();i++) {
array[i] = list.get(i);
}
return array;
}
附:链表反转
public static ListNode reverse(ListNode head) {
ListNode pre = head;
ListNode cur = head.next;
ListNode next = null;
head.next = null;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
public static ListNode reverse1(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode next = null;
// next = 2
// pre = 0
// cur = 1
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
网友评论