/**
* 数组转链表
* @param arr
* @return
*/
public ListNode arrayToNode(int[] arr){
if (arr.length == 0){
return null;
}
ListNode root = new ListNode();
ListNode rootIndex = root;
for (int i = 0; i < arr.length; i++) {
ListNode listNode = new ListNode(arr[i]);
rootIndex.next = listNode;
rootIndex = rootIndex.next;
}
return root.next;
}
/**
* 打印链表
* @param listNode
*/
public void printNode(ListNode listNode){
ListNode index = listNode;
List<Integer> res = new ArrayList<>();
while (index != null){
res.add(index.val);
index = index.next;
}
System.out.println(Arrays.toString(res.toArray()));
}
/**
* Node代码
*/
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
数组转链表
于 2024-01-20 14:47:44 首次发布