package datastruct;
/* *双向链表的的结点 */ public class DoubleNode { private DoubleNode previous;// 指向前一个接点的指针 private int value;// 接点保存的值 private DoubleNode next;// 指向下一个接点的指针
public DoubleNode(int value) { super(); this.value = value; this.previous = this;//初始时指向自身 this.next = this;//初始时指向自身 }
public DoubleNode() { // TODO Auto-generated constructor stub }
public DoubleNode getPrevious() { return previous; }
public void setPrevious(DoubleNode previous) { this.previous = previous; }
public int getValue() { return value; }
public void setValue(int value) { this.value = value; }
public DoubleNode getNext() { return next; }
public void setNext(DoubleNode next) { this.next = next; }
}
package datastruct; /** * 双向链表 * @author dell * */ public class MyDoubleList {
private DoubleNode head;// 头结点,初始值为null private int length = 0;// 链表的长度
public int getLength() { return length; }
public void setLength(int length) { this.length = length; }
public MyDoubleList() { head = new DoubleNode(); }
public DoubleNode getHead() { return head; }
public void setHead(DoubleNode head) { this.head = head; }
/** * @param args */ public static void main(String[] args) { MyDoubleList ml = new MyDoubleList(); ml.add(new DoubleNode(1)); ml.add(new DoubleNode(2)); ml.add(new DoubleNode(3)); ml.add(new DoubleNode(4)); ml.add(new DoubleNode(5)); ml.add(new DoubleNode(6)); ml.add(new DoubleNode(7)); ml.remove(new DoubleNode(3)); ml.insert(new DoubleNode(11), 3);
while (ml.head != null) { System.out.println(ml.head.getValue()); ml.head = ml.head.getPrevious(); } }
/** * 添加新节点 * * @param n要加入的节点 */ public void add(DoubleNode n) { head.setNext(n);//头结点的next指针指向n //n的前驱指针指向head n.setPrevious(head); head = n;// 指针移动 this.length++; }
/** * 删除某个节点 * * @param n要删除的节点 */ public void remove(DoubleNode n) { if (head == null) return; if (n.getValue() == this.head.getValue()) { head = head.getPrevious(); head.setNext(null); // head.setp return; }
DoubleNode pre = head;// 当前节点,初始值为头结点 DoubleNode cur = head.getPrevious();// 当前节点的前驱节点 while (cur != null) { if (cur.getValue() == n.getValue()) { pre.setPrevious(cur.getPrevious()); cur.getPrevious().setNext(pre); // pre.getNext().setNext(cur.getNext()); return;// }
pre = pre.getPrevious();// 移动指针 cur = cur.getPrevious();// 移动指针 }
}
/** *插入节点 */ public void insert(DoubleNode n, int i) { if (head == null) { add(n); return; }
DoubleNode pre = head; DoubleNode cur = head.getPrevious(); int j = 1; while (cur != null) { if (j == i-1) { cur.setNext(n); n.setPrevious(cur); n.setNext(pre); pre.setPrevious(n); return; }
pre = pre.getPrevious();// 移动指针 cur = cur.getPrevious();// 移动指针 j++; }
} }
