结构类

1.链表结构体
public class ListNode {

public int data;

public ListNode next;

public ListNode random;//随机指针

public ListNode(int data) {
this.data = data;
}

public int getData() {
return data;
}

public void setData(int data) {
this.data = data;
}

public ListNode getNext() {
return next;
}

public void setNext(ListNode next) {
this.next = next;
}

public ListNode getRandom() {
return random;
}

public void setRandom(ListNode random) {
this.random = random;
}

/**
* 打印链表
*/
public void print() {
List<Integer> list = Lists.newArrayList();
list.add(data);
while (next != null) {
list.add(next.data);
next = next.next;
}
System.out.println(list);
}

}

2.创建链表
public class CreateNode {
private ListNode head;

public CreateNode(List<Integer> list) {
ListNode head = new ListNode(list.get(0));
ListNode cur = head;
for (int i = 1; i < list.size(); i++) {
ListNode temp = new ListNode(list.get(i));
cur.setNext(temp);
cur = temp;
}
this.head = head;
}

public ListNode getHead() {
return head;
}

public void setHead(ListNode head) {
this.head = head;
}
}
3.打印
public static void main(String[] args) {
List<Integer> list = Arrays.asList(23, 34, 55, 6, 5, 35, 677, 2);
ListNode listNode = new CreateNode(list).getHead();
List<Integer> returnList = print(listNode);
returnList.forEach(System.out::println);
}
4.二叉树
public class BinaryTree {
public int data;//根节点数据
public BinaryTree left;//左子树
public BinaryTree right;//左子树

public BinaryTree next;

public BinaryTree(int data) {
this.data = data;
left = null;
right = null;
}

public void batchInsert(BinaryTree root, List<Integer> data) {
if (root == null || CollectionUtils.isEmpty(data)) {
return;
}
for (int i = 0; i < data.size(); i++) {
insert(root, data.get(i));
}
}

public void insert(BinaryTree root, int data) {
if (data > root.data) { // 右子节点
if (root.right == null) {
root.right = new BinaryTree(data);
}else {
insert(root.right, data);
}
}else {
if (root.left == null) {
root.left = new BinaryTree(data);
}else {
insert(root.left, data);
}
}
}

/**
* //先序遍历
* @param root
*/
public static void preOrder(BinaryTree root){
if (root!=null) {
System.out.print(root.data+" ");
preOrder(root.left);
preOrder(root.right);
}
}

/**
* //中序遍历
* @param root
*/
public static void inOrder(BinaryTree root){
if(root!=null){
inOrder(root.left);
System.out.print(root.data+" ");
inOrder(root.right);
}
}

/**
* //后续遍历
* @param root
*/
public static void postOrder(BinaryTree root){
if (root!=null) {
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data+" ");
}
}

/**
Binary Search Tree(BSTree)二叉查找树
在二叉查找树中:
(01) 若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(02) 任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(03) 任意节点的左、右子树也分别为二叉查找树。
(04) 没有键值相等的节点(no duplicate nodes)。
*/
}

5.打印
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree(8);
binaryTree.batchInsert(binaryTree, Lists.newArrayList(6, 10, 5, 7, 9, 11));
}
posted @ 2021-05-10 10:25  何其小静  阅读(120)  评论(0编辑  收藏  举报