双链表的插入删除


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值