数据结构--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); } }
相关文章推荐
- 使用java实现双向链表数据结构
- [java数据结构]--java双向链表LinkedList的简单实现
- 双向链表-数据结构-java实现
- java与数据结构(4)---java实现双向循环链表
- java数据结构之实现双向链表的示例
- java数据结构:双向链表结构与实现
- java 实现双向链表(数据结构)
- 数据结构之循环双向链表java实现
- Java简单双向链表实现 @version 1.0
- Java的单链表与双向链表的实现
- 剑指offer----二叉搜索树与双向链表----java实现
- 【Java数据结构】2.1单链表的实现
- 数据结构双向循环链表的C语言实现(插入,查询,删除)
- C实现通用数据结构--双向链表
- Java实现双向链表
- JAVA实现双向链表的增删功能的方法
- java实现双向链表
- java实现双向链表
- 【JAVA数据结构】 简单链表的实现
- java实现数据结构之单向链表