// Definition for singly-linked list.publicstaticclassListNode{int val;
ListNode next;ListNode(int x){
val = x;}}
1.2 构建单链表:
1.2.1 ListNodeUtil类:
publicstaticclassListNodeUtil{// 构建链表publicstatic ListNode createLinkedList(int[] arr){// 将输入的数组输入到链表中if(arr.length ==0){return null;}
ListNode head =newListNode(arr[0]);
ListNode current = head;for(int i =1; i < arr.length; i++){// 过程
current.next =newListNode(arr[i]);
current = current.next;}return head;}// 打印链表publicstaticvoidprintLinkedList(ListNode head){// 将链表结果打印
ListNode current = head;while(current != null){
System.out.printf("%d -> ", current.val);
current = current.next;}
System.out.println("NULL");}}
1.2.2 Main类:
import java.util.*;publicclassMain{publicstaticvoidmain(String[] args){int[] x ={1,2,3,4,5,6};
ListNode list = ListNodeUtil.createLinkedList(x);
ListNodeUtil.printLinkedList(list);}}
2. 二叉树:
2.1 二叉树结点:
// Definition for a binary tree node.publicstaticclassTreeNode{int val;
TreeNode left;
TreeNode right;TreeNode(int x){
val = x;}}