首页 > 程序开发 > 软件开发 > Java >

Java数据结构--双向链表

2017-05-09

Java数据结构--双向链表。

Java实现双向链表

双向链表:每个结点有包含两个指针,一个指向前一个结点的引用,一个指向后一个结点的引用;

结点类

package DoubleLink;

/**
 * Created by Zz on 2017/5/5 0005.
 */
public class Node {
    public Node next;
    public Node previous;
    private int data;

    public Node(int data) {
        this.data = data;
    }
    public String toString(){
        return data+" ";
    }

    public int getData() {
        return data;
    }

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

    public boolean equals(Object other) {
        Node temp = null;
        if (other instanceof Node) {
            temp = (Node)other;
            if (temp.getData() == this.getData()) {
                return true;
            }else  {
                return false;
            }
        }else {
            return false;
        }
    }
}

DoubleLink实现

package DoubleLink;

/**
 * Created by Zz on 2017/5/5 0005.
 */
public class DoubleLink {
    private Node first;
    private Node end;
    public void addFirst(int data) {
        Node node = new Node(data);
        if (first!=null) {
            node.next = first;
            first.previous = node;
            first = node;
        } else {
            first = node;
            end = node;
        }
    }

    public void addEnd(int data) {
        Node node = new Node(data);
        if(end!=null) {
            end.next = node;
            node.previous = end;
            end = node;
        } else {
            first = node;
            end = node;
        }
    }

    public Node find(int data) {
        Node temp = new Node(data);
        Node f = first;
        while (f!=null) {
            if (f.equals(temp))
                break;
            else
                f = f.next;
        }
        return f;
    }

    public void delete(int data) {
        Node node = find(data);
        if (node!=null) {
            node.previous.next = node.next;
            node.next.previous = node.previous;
        }
    }

    public void update(int ydata,int mdata) {
        Node node = find(ydata);
        node.setData(mdata);
    }

    public String toString() {
        StringBuffer stringBuffer = new StringBuffer();
        Node temp = first;
        while (temp!=null) {
            if (temp == end)
                stringBuffer.append("["+temp.getData()+"]");
            else
                stringBuffer.append("["+temp.getData()+"]"+",");
            temp = temp.next;
        }
        return stringBuffer.toString();
    }
}

运行结果:

 public static void main(String[] args) {
        DoubleLink doubleLink = new DoubleLink();
        doubleLink.addFirst(10);
        doubleLink.addFirst(20);
        doubleLink.addFirst(30);
        doubleLink.addEnd(40);
        doubleLink.addEnd(50);
        System.out.println(doubleLink.toString());
    }
[30],[20],[10],[40],[50]
相关文章
最新文章
热点推荐