双链表的插入删除
2015-06-10 10:22
176 查看
public class DoubleLinkedList { public Node head; public DoubleLinkedList() { head = new Node(); head.next = null; head.prior = null; } //尾插法 public void createByTail(int[] arr, int n) { Node tail = head; for(int i=0; i<n; i++) { Node c = new Node(arr[i]); tail.next = c; c.prior = tail; tail = c; } tail.next = null; } //头插法 public void createByHead(int[] arr, int n) { for(int i=0; i<n; i++) { Node c = new Node(arr[i]); c.next = head.next; c.prior = head; if(head.next != null) head.next.prior = c; head.next = c; } } //插入一个节点 public boolean insert(int i, int e) { int j=0; Node p = head; while(j<i-1 && p!=null) { j++; p = p.next; } if(p == null) { return false; } Node c = new Node(e); c.next = p.next; c.prior = p; if(p.next != null) { p.next.prior = c; } p.next = c; return true; } //删除一个节点 public int[] delete(int i) { int[] arr = new int[2]; int j=0; Node p = head; while(j<i-1 && p!=null) { j++; p = p.next; } if(p == null ||p.next == null) { arr[0] = 0; return arr; } arr[0] = 1; arr[1] = p.next.data; p.next = p.next.next; if(p.next !=null) p = p.next.prior ; return arr; } public void display() { Node p = head.next; while(p != null) { if(p.next != null) System.out.print(p.data + "->"); else System.out.println(p.data); p = p.next; } } public static void main(String[] args) { int[] arr = new int[]{5,6,1,6,9,3,7,8,10,11,4}; DoubleLinkedList list = new DoubleLinkedList(); list.createByHead(arr, arr.length); list.display(); list.createByTail(arr, arr.length); list.display(); if(!list.insert(13, 99)) { System.out.println("error"); } else { list.display(); } if(!list.insert(10, 99)) { System.out.println("error"); } else { list.display(); } int[] tmp = list.delete(12); if(tmp[0] == 0) { System.out.println("error"); } else { System.out.println("delete " + tmp[1]); list.display(); } tmp = list.delete(4); if(tmp[0] == 0) { System.out.println("error"); } else { System.out.println("delete " + tmp[1]); list.display(); } } } class Node { public int data; public Node next; public Node prior; public Node(){} public Node(int data) { this.data = data; next = prior = null; } }
结果:
4->11->10->8->7->3->9->6->1->6->5 5->6->1->6->9->3->7->8->10->11->4 error 5->6->1->6->9->3->7->8->10->99->11->4 delete 4 5->6->1->6->9->3->7->8->10->99->11 delete 6 5->6->1->9->3->7->8->10->99->11
相关文章推荐
- iOS 关于展示PDF文件处理
- When a QThread isn't a thread...
- CAN总线与LIN终端配置方法
- 关于ADO.NET中的几大对象的介绍使用的个人心得
- Leetcode[203]-Remove Linked List Elements
- SQL纯手写创建数据库到表内内容
- (二)SSO之CAS框架单点退出,自定义退出界面.
- jquery判断复选框是否被选中
- 使用java反射技术完成对象所有属性值的输出
- Python包管理:pip、easy_install、eggs和wheel
- 具备了这四大特性您的网站就成了优秀的网站
- MapReduce小文件处理之CombineFileInputFormat实现
- 从HelloWorld开始
- 通过代理进行页面传值
- C#IM开发误区
- 关于Js、jq css html常用属性的笔记
- C语言指向函数的指针
- 渣渣ACM日记——1012-u Calculate e (HDOJ)
- Matlab数值计算
- Android(安卓)内存分配机制详解 不需要关闭后台运行程序