Java数据结构与算法(三)链表

Java数据结构与算法(三)链表

数组是连续空间,按照下标查询很快。
数组有删除和添加到特定位置需要移动大量下标的操作很慢。

在Java中链表就没有什么定义了,完全使用类(通常叫Node或者Entry)来表示的。

单向链表

static class Node<T> {
    private T t;
    private Node<T> next;
    public Node(T t) {
        this.t = t;
    }

}

成员

private Node<T> head = null;
private Node<T> tail= null;

addLast方法

public void addLast(T t) {
    Node<T> node = new Node<T>(t);

    if(head == null) {
        tail = head = node;
        return;
    }
    tail.next = node;
    tail = node;
}

addFirst方法

public void addFirst(T t) {
    Node<T> node = new Node<T>(t);
    if(head == null) {
        tail = head = node;
        return;
    }
    node.next = head;
    head = node;
}

removeNode方法

public boolean removeNode(T t){
    Node<T> tmp = head;
    if(tmp.t.equals(t)) {
        head = tmp.next;
        return true;
    }


    while(tmp.next!=null) {

        if(tmp.next.t.equals(t)) {
            tmp.next = tmp.next.next;//如果是最后一个会导致tail为空的
            return true;    
        }
        tmp = tmp.next;
    }
    return false;
}

contains方法

public boolean contains(T t) {
    Node<T> tmp = head;
    while(tmp!=null) {

        if(tmp.t.equals(t)) {
            return true;
        }
        tmp = tmp.next;
    }
    return false;
}

拓展:反转单链表reverse(Node head)

public void reverse(Node<T> head) {

    if(head == null|| head.next == null) {
        return;
    }

    Node<T> tmp = head;//bbbb
    Node<T> cursor = head.next;//aaaa
    tmp.next = null;
    Node<T> cursorNext =null ; 
    while(cursor!=null) {
        cursorNext = cursor.next;
        head = cursor;
        head.next=tmp;
        tmp = head;
        cursor = cursorNext;
    }

    //打印
    Node<T> node2 = head;
    while(node2!=null){
        System.out.print(node2.t+"--->");
        node2 = node2.next;
    }

}

去掉打印,代码就没几行了,看起来很简单,但是也得想一会,算法就是这样子。

猜你喜欢

转载自blog.csdn.net/mayongzhan_csdn/article/details/81190498