package com.itjob.structure;

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() {
		// 不要直接使用String类，存在效率问题
		StringBuffer sb = new StringBuffer();
		Node temp = first;
		while (temp != null) {
			if (temp == end)
				sb.append("[" + temp.getData() + "]");
			else
				sb.append("[" + temp.getData() + "],");
			temp = temp.next;
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
		DoubleLink dl = new DoubleLink();
		dl.addFirst(30);
		dl.addFirst(40);
		dl.addFirst(50);
		dl.addFirst(60);
		dl.addEnd(70);
		dl.addEnd(80);
		dl.addEnd(90);
		dl.delete(50);
		System.out.println(dl);
	}
}