数据结构基本实现

数组

package com.jd.trade.sdk.domain.core.licy.array;

import com.jd.trade.sdk.domain.core.licy.List;

/**
 * 顺序表
 */
public class SequenceList implements List {

    private static final int defaultSize = 10;

    //当前元素的个数
    private int size;

    private int maxSize;

    private Object[] data;

    public SequenceList() {
        init(defaultSize);
    }

    public SequenceList(int size) {
        init(size);
    }

    private void init(int maxSize) {
        this.maxSize = maxSize;
        this.size = 0;
        this.data = new Object[maxSize];
    }


    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void insert(int index, Object object) throws Exception {

        if (size == maxSize) {
            throw new Exception("满了");
        }
        if (index < 0 || index > size) {
            throw new Exception("越界");
        }
        for (int i = size; i > index; i--) {
            data[i] = data[i-1];
        }

        data[index] = object;

        size++;
    }

    @Override
    public Object get(int index) throws Exception {
        if (index < 0 || index >= size) {
            throw new Exception("越界");
        }

        return data[index];
    }

    @Override
    public void delete(int index) throws Exception {
        if (index < 0 || index >= size) {
            throw new Exception("out of");
        }
        if (isEmpty()) {
            throw new Exception("is null");
        }
        for (int i = index; i < size-1; i++) {
            data[i] = data[i+1];
        }
        size--;

    }
}

链表

package com.jd.trade.sdk.domain.core.licy.link;

import com.jd.trade.sdk.domain.core.licy.List;
import com.jd.trade.sdk.domain.core.licy.Node;

public class LinkedList implements List {
    Node head;

    int size;

    Node cur;

    public LinkedList() {
        head = cur = new Node(null);
    }

    /**
     * 定位到index对应节点
     *
     * @param index
     * @throws Exception
     */
    public void index(int index) throws Exception {
        //-1 是head节点
        if (index < -1 || index >= size) {
            throw new Exception("");
        }
        if (index == -1)return;

        int i = 0;
        cur = head.next;
        while (cur != null && i < index) {
            cur = cur.next;
            i++;
        }
    }

    @Override
    public void insert(int index, Object object) throws Exception {
        if (index < 0 || index > size) {
            throw new Exception("");
        }

        index(index-1);

        cur.setNext(new Node(object, cur.next));
        size++;
    }

    @Override
    public Object get(int index) throws Exception {
        if (index < 0 || index >= size) {
            throw new Exception();
        }

        index(index);

        return cur.getData();
    }

    @Override
    public void delete(int index) throws Exception {
        if (index < 0 || index >= size) {
            throw new Exception();
        }

        index(index-1);

        cur.setNext(cur.next.next);
        size--;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }
}

package com.jd.trade.sdk.domain.core.licy.stack;

import com.jd.trade.sdk.domain.core.licy.Stack;

public class SequenceStack implements Stack {

    Object[] arrs;
    int top;
    int maxSize;

    public SequenceStack() {
        init (10);
    }

    public SequenceStack(int maxSize) {
        init(maxSize);
    }

    private void init(int maxSize) {
        this.maxSize = maxSize;
        arrs = new Object[maxSize];
        top = 0;
    }

    @Override
    public void push(Object o) {
        if (top == maxSize) {
            throw new RuntimeException("full");
        }
        arrs[top] = o;
        top++;
    }

    @Override
    public Object pop() {
        if (top == 0) {
            throw new RuntimeException("null");
        }
        top--;

        return arrs[top];
    }

    @Override
    public Object getTop() {
        return arrs[top-1];
    }

    @Override
    public boolean isEmpty() {
        return top == 0;
    }

    public static void main(String[] args) throws Exception {
        SequenceStack sequenceStack = new SequenceStack(10);
        sequenceStack.push(0);
        sequenceStack.push(1);
        sequenceStack.push(2);
        System.out.println(sequenceStack.getTop());

        while (!sequenceStack.isEmpty()) {
            System.out.println(sequenceStack.pop());
        }

        signCheck("((()())");
        expCaculate(new LinkedStack());
    }

    /**
     * 括号匹配问题
     *
     * @param exp
     */
    public static void signCheck(String exp) {
        SequenceStack stack = new SequenceStack();
        char[] cs = exp.toCharArray();
        for (int i = 0; i < cs.length; i++) {
            if (cs[i] == '(') {
                stack.push(cs[i]);
            }else if (cs[i] == ')' && !stack.isEmpty() && (char)stack.getTop() != '(') {
                System.out.println("不匹配");
                return;
            }else if (cs[i] == ')' && !stack.isEmpty() && (char)stack.getTop() == '(') {
                stack.pop();
            }else if (cs[i] == ')' && stack.isEmpty()){
                System.out.println("右边多于左边");
                return;
            }
        }
        if (!stack.isEmpty()) {
            System.out.println("左边 多于右边");
        }else {
            System.out.println("匹配");
        }
    }

    /**
     * 后缀表达式计算
     *
     * @param stack
     * @throws Exception
     */
    public static void expCaculate(LinkedStack stack) throws Exception {
        char ch;
        int x1 = 0, x2;
        while ((ch = (char)System.in.read()) != '#') {
            if (Character.isDigit(ch)) {
                stack.push(new Integer(Character.toString(ch)));
            }else {
               x2 =  ((Integer)stack.pop()).intValue();
               x1 =  ((Integer)stack.pop()).intValue();
               switch (ch) {
                   case '+' :
                       x1 += x2; break;
                   case '-' :
                       x1 -= x2; break;
                   case '*' :
                       x1 *= x2; break;
                   case '/' :
                       if (x2 == 0) throw new RuntimeException("chushu is 0");
                       x1 /= x2;break;
               }
               //注意 这个要把结果放入栈中
               stack.push(x1);
            }
        }
        System.out.println(stack.getTop());
    }

}

队列

package com.jd.trade.sdk.domain.core.licy.queue;

import com.jd.trade.sdk.domain.core.licy.Queue;

/**
 * 循环顺序对列
 */
public class CircleSequenceQueue implements Queue {

    Object[] data;

    int front;
    int rear;
    int maxSize;

    //判断是否满
    int count;

    public CircleSequenceQueue() {
        init(10);
    }

    public CircleSequenceQueue(int maxSize) {
        init(maxSize);
    }

    private void init(int maxSize) {
        this.maxSize = maxSize;
        data = new Object[maxSize];
        front = rear = 0;
        count = 0;
    }

    /**
     * 入队 操作对尾指针
     *
     * @param o
     * @throws Exception
     */
    @Override
    public void append(Object o) throws Exception {
        if (count > 0 && front == rear) {
            throw new Exception("full");
        }
        data[rear] = o;
        rear = (rear+1)%maxSize;
        count++;
    }

    /**
     * 出队 操作队头指针
     *
     * @return
     * @throws Exception
     */
    @Override
    public Object delete() throws Exception {
        if (isEmpty()) {
            throw new Exception("null");
        }
        Object o = data[front];
        front = (front+1)%maxSize;
        count--;
        return o;
    }

    @Override
    public Object getFront() throws Exception {
        if (isEmpty()) {
            return null;
        }
        return data[front];
    }

    @Override
    public boolean isEmpty() {
        return count == 0;
    }

    public static void main(String[] args) throws Exception {
        CircleSequenceQueue queue = new CircleSequenceQueue();
        queue.append("a");
        queue.append("b");
        queue.append("c");
        queue.append("d");

        queue.delete();
        queue.delete();
        queue.append("e");
        queue.append("f");
        while (!queue.isEmpty()) {
            System.out.println(queue.delete());
        }
    }
}

售票窗口设计

package com.jd.trade.sdk.domain.core.licy.queue;

/**
 * 卖票窗口
 */
public class WindowQueue {
    int size = 10;
    CircleSequenceQueue queue = new CircleSequenceQueue(size);

    int num = 0;
    volatile boolean isAlive = true;


    public synchronized void producer() throws Exception {
        if (queue.count < size) {
            //没满
            queue.append(num++);
            System.out.println("第" + num + "个客户排队买票");

            this.notifyAll();
        }else {
            try {
                System.out.println("队列已满 -- 请等待");
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void consumer() throws Exception {
        if (queue.count > 0) {
            Integer data = (Integer) queue.delete();

            System.out.println("第" + (data+1) + "个客户买票离开");

            if (queue.isEmpty() && this.num >= 100) {
                System.out.println("票已卖完");
                isAlive = false;
            }

            this.notifyAll();
        }else {
            try {
                System.out.println("队列已空 -- 请等待");
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        WindowQueue queue = new WindowQueue();
        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);
        Thread pThread = new Thread(producer);
        Thread cThread = new Thread(consumer);
        pThread.start();
        cThread.start();
    }
}
package com.jd.trade.sdk.domain.core.licy.queue;

public class Producer implements Runnable {
    WindowQueue queue;

    public Producer(WindowQueue queue) {
        this.queue = queue;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        while (queue.num < 100) {
            try {
                queue.producer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

package com.jd.trade.sdk.domain.core.licy.queue;

public class Consumer implements Runnable {
    WindowQueue queue;

    public Consumer(WindowQueue queue) {
        this.queue = queue;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        while (queue.isAlive) {
            try {
                queue.consumer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

字符串

package com.jd.trade.sdk.domain.core.licy.string;

import java.util.Arrays;

public class MyString {
    char[] data;
    int size;

    public MyString() {
        data = new char[0];
        size=0;
    }

    public MyString(String s) {
        data = s.toCharArray();
        size = s.length();
    }
    public MyString(char[] data, int offset, int length) {
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (length < 0) {
            throw new StringIndexOutOfBoundsException(length);
        }
        if(offset+length > data.length) {
            throw new StringIndexOutOfBoundsException(offset+length);
        }
        this.data = new char[length];
        this.size = length;
        arrayCopy(data, offset, this.data, 0, length);
    }

    private void arrayCopy(char[] src, int srcPos, char[] target, int targetPos, int length) {
        if (srcPos+length > src.length) {
            throw new StringIndexOutOfBoundsException(srcPos+length);
        }
        if (targetPos+length > target.length) {
            throw new StringIndexOutOfBoundsException(targetPos+length);
        }
        for (int i = 0; i < length; i++) {
            target[targetPos++] = src[srcPos++];
        }
    }

    public int compare(MyString another) {
        char[] v1 = data;
        char[] v2 = another.data;
        int n = Math.min(v1.length, v2.length);
        for (int i = 0; i < n; i++) {
            char c1 = v1[i];
            char c2 = v2[i];
            if (c1 != c2) {
                return c1-c2;
            }
        }
        return v1.length-v2.length;
    }

    public MyString substring(int begin, int end) {
        return new MyString(data, begin, end-begin);
    }
    public MyString substring(int begin) {
        return substring(begin, this.size);
    }

    public MyString concat (MyString myString) {
        if (myString.size == 0) {
            return this;
        }
        char[] buff = new char[myString.size + this.size];
        arrayCopy(data, 0, buff, 0, size);
        arrayCopy(myString.data, 0, buff, size, myString.size);
        return new MyString(buff, 0, buff.length);
    }

    public MyString insert(MyString myString, int pos) {
        if (pos == 0) {
            return this.concat(myString);
        }else {
            MyString myString1 = this.substring(0, pos);
            MyString concat = myString1.concat(myString);
            MyString res = concat.concat(this.substring(pos));
            return res;
        }
    }

    public MyString delete(int begin, int end) {
        if (begin ==0 && end-begin == size) {
            return new MyString();
        }
        MyString substring = this.substring(0, begin);
        return substring.concat(this.substring(end));
    }
    @Override
    public String toString() {
        String s = "";
        for (int i = 0; i < data.length; i++) {
            s += data[i];
        }
        return s;
    }

    public static void main(String[] args) {
        char[] c1 = {'l','o','v','e'};
        char[] c2 = {'L','o','v','e'};
        MyString s1 = new MyString(c1, 0, 4);
        MyString s2 = new MyString(c2, 0, 4);
        System.out.println(s1);
        System.out.println(s1.compare(s2));

        System.out.println(s1.substring(1, 4));
        System.out.println(s1.concat(s2));
        System.out.println(s1.insert(new MyString(" you"), 1));
        System.out.println(s1.delete(1,3));
    }
}

public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}

返回树中某一深度的所有节点


public class TreeLevel {
    ListNode pre = new ListNode(-1);
    ListNode cur = pre;
    public ListNode getTreeLevel(TreeNode root, int dep) {
        // write code here
        if (root == null || dep <= 0) {
            return null;
        }
        if (dep == 1) {
            cur.next = new ListNode(root.val);
            cur = cur.next;
        }else {
            getTreeLevel(root.left, dep-1);
            getTreeLevel(root.right, dep-1);
        }
        return pre.next;
    }
 
}

/**
     * 深度优先搜索(递归)
     */
    private boolean checkDFS(UndirectedGraphNode a, UndirectedGraphNode b) {
 
 
        if (a == null || b == null) {
            return false;
        }
        if (a == b) {
            return true;
        }
 
        visitedMap.put(a, true);
 
        for (UndirectedGraphNode neighbor : a.neighbors) {
            if (!visitedMap.containsKey(neighbor) && checkDFS(neighbor, b)) {
                return true;
            }
        }
 
        return false;
 
    }
 
    /**
     * 广度优先搜索
     */
    private boolean checkBFS(UndirectedGraphNode a, UndirectedGraphNode b) {
 
        if (a == null || b == null) {
            return false;
        }
        if (a == b) {
            return true;
        }
 
        Queue<UndirectedGraphNode> queue = new LinkedList();
        Map<UndirectedGraphNode, Boolean> visited = new HashMap<>();
        visited.put(a, true);
        queue.add(a);
        while (!queue.isEmpty()) {
            UndirectedGraphNode node = queue.remove();
            for (UndirectedGraphNode neighbor : node.neightbors) {
                if (!visited.containsKey(neighbor)) {
                    
                    if (neighbor == b) return true;
                    
                    visited.put(neighbor, true);
                    queue.add(neighbor);
                }
            }
        }
 
        return false;
    }

 

内含资源如下: 1.基本数据结构 1.1.Array ........... 动态数组 1.2.LinkedList ... 链表 1.3.BST .............. 二分搜索树 1.4.MapBST ..... 二分搜索树(用于实现映射) 1.5.AVLTree ...... AVL树 2.接口 2.1.Queue ........... 队列接口 2.2.Stack .............. 栈接口 2.3.Set .................. 集合接口 2.4.Map ............... 映射接口 2.5.Merger .......... 自定义函数接口 2.6.UnionFind ..... 并查集接口 3.高级数据结构 3.1.ArrayQueue .......................... 队列_基于动态数组实现 3.2.LinkedListQueue .................. 队列__基于链表实现 3.3.LoopQueue ........................... 循环队列_基于动态数组实现 3.4.PriorityQueue ....................... 优先队列_基于最大二叉堆实现 3.5.ArrayPriorityQueue ............. 优先队列_基于动态数组实现 3.6.LinkedListPriorityQueue ..... 优先队列_基于链表实现 3.7.ArrayStack ............................. 栈_基于动态数组实现 3.8.LinkedListStack ..................... 栈_基于链表实现 3.9.BSTSet ..................................... 集合_基于二分搜索树实现 3.10.LinkedListSet ....................... 集合_基于链表实现 3.11.BSTMap ................................ 映射_基于二分搜索树实现 3.12.AVLTreeMap ....................... 映射_ 基于AVL树实现 3.13.LinkedListMap .................... 映射_基于链表实现 3.14.MaxHeap ............................. 最大二叉堆 3.15.SegmentTree ...................... 线段树 3.16.Trie ......................................... 字典树 3.17.QuickFind ............................ 并查集_基于数组实现 3.18.QuickUnion ......................... 并查集_基于树思想实现
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值