您的位置:首页 > 理论基础 > 数据结构算法

数据结构--java实现双向链表

2014-04-22 18:22 681 查看
使用java实现双向链表的逻辑

package com;

/*
* 双向链表链表类
*/
public class DLink {

DLNode head, p, q, l;// 头引用head,p定位,q为待插入节点的引用
int n = 0;// 节点数目

// 构造空双向链表
public DLink() {
head = null;
}

// 构造非空双向链表
public DLink(DLNode h) {
head = h;
}

// 判断双向链表是否为空
public boolean isEmpty() {
return head == null;
}

/*
* 插入节点(1空插入,2中间插入,3首尾插入) 按num小到大插入
*/
public void insert(int num) {
// 空插入
if (this.isEmpty()) {
head = new DLNode(num);
this.n++;
} else// 下为非空插入
{
p = head;
// 定位
while (p.next != null) {
if (p.num == num)
break;
if (num > p.num && num < p.next.num) {
// System.out.println("break p:"+p.num);
break;
}
p = p.next;
}
// 插入在首尾
if (n == 1 || p.next == null) {
// 首
if (head.num >= num) {
q = new DLNode(num);
q.next = head;
q.prior = null;
head.prior = q;
this.head = q;
this.n++;
}
// 尾
else {
q = new DLNode(num);
p.next = q;
q.next = null;
q.prior = p;
this.n++;
}
}
// 插在中间
else {

q = new DLNode(num);
q.next = p.next;
q.prior = p;
p.next.prior = q;
p.next = q;
this.n++;
}
}
}

// 输出h指向的节点
public void output(DLNode h) {
System.out.print(h.num);
}

// 遍历
public void Travel() {
p = this.head;
while (p != null) {
this.output(p);
System.out.print("----");
p = p.next;
}
}

// 节点个数
public int getnum() {
System.out.println("L's length is " + n);
return n;
}

// 删除节点
public void delete(int num) {
boolean flag = false;// 标志是否存在
// 查找
p = this.head;
while (p != null) {
if (p.num == num) {
flag = true;
break;
}
p = p.next;
}
// 存在,删除(第一个节点,中间节点,末尾节点)
if (flag) {
if (p == head) {
head = p.next;
head.prior = null;
System.out.println("delete(1) " + num);
this.n--;
} else if (p.next == null) {
DLNode temp = p.prior;
temp.next = null;
System.out.println("delete(2) " + num);
this.n--;
} else {
p.prior.next = p.next;
p.next.prior = p.prior;
System.out.println("delete(3) " + num);
this.n--;
}

} else {
System.out.println("无可删除节点!");
}
}

// 测试
public static void main(String[] args) {
DLNode head = null;
DLink L = new DLink(head);
L.insert(0);
L.insert(1);
L.insert(5);
L.insert(3);
L.insert(-9);
L.insert(2);

L.Travel();
L.getnum();
L.delete(0);
L.Travel();
L.delete(5);
L.Travel();
L.delete(1);
L.Travel();
L.getnum();
}

}

package com;

/*
* 双向链表节点
*/
public class DLNode {
int num;
DLNode next, prior;

// 构造节点
public DLNode(int num) {
this.num = num;
next = null;
prior = null;
}

public DLNode() {
this(0);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: