码迷,mamicode.com
首页 > 其他好文 > 详细

双链表的插入删除

时间:2015-06-10 12:27:42      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

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

双链表的插入删除

标签:

原文地址:http://blog.csdn.net/qhairen/article/details/46438747

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!