java数据结构(双向链表)

双向链表也是一个特殊的链表,它跟单链表一样有指向下一个元素的指针,但是也有指向前一个元素的指针,这样方便找到前一个元素。

先设计Node类

package com.dzl.sjjg.ovoniclinklist;


public class Node {

	
	Object element;
	Node next;
	Node prior;
	
	public Node(Node priorval,Node nextval) {
		// TODO Auto-generated constructor stub
		next = nextval;
		prior = priorval;
	}
	
	public Node(Node priorval,Node nextval,Object object) {
		// TODO Auto-generated constructor stub
		next = nextval;
		prior = priorval;
		element = object;
	}

	public Object getElement() {
		return element;
	}

	public void setElement(Object element) {
		this.element = element;
	}

	public Node getNext() {
		return next;
	}

	public void setNext(Node next) {
		this.next = next;
	}

	@Override
	public String toString() {
		return element.toString();
	}
	
	
}

之后就是双向链表的设计

package com.dzl.sjjg.ovoniclinklist;


public class ovonicLinkList {

	Node head;
	Node current;
	int size;
	
	ovonicLinkList(){
		head = current =new Node(null,null);
		size =0;
	}
	
	public Object getElem(int i){
		Node p =  head;
		int j = 1;
		while (ji+1) return null;
		return p.element;
	}
	
	public boolean insert(int i ,Object e){
		Node p =  head;
		int j = 1;
		while (ji) return false;
		Node s  =  new Node(null,null);
		s.element = e;
		
		//s的前驱后继
		s.prior =  p;
		s.next = p.next;
	
		//p .next的前驱后继
		if(p.next!=null)
		p.next.prior =  s;
		p.next = s;
		
		size++;
		return true;
	}
	
	
	public boolean delete(int i ){
		Node p =  head;
		int j = 1;
		while (ji) return false;
		if(p.prior!=null)
		p.prior.next = p.next;
		p.next.prior  =  p.prior;
		size--;
		return true;
	}
	
	public void showall(){
		Node p =  head;

		while (p.next!=null) {
			p =  p.next;
			System.out.print(p.element+" ");
		}
		System.out.println();
	}
}

测试代码

package com.dzl.sjjg.ovoniclinklist;

public class test {
	public static void main(String[] args) throws Exception {
	
		ovonicLinkList list = new ovonicLinkList();
		System.out.println(list.insert(1, 44));
		System.out.println(list.insert(2, 42));
	
		list.showall();
		System.out.println(list.delete(1));
		System.out.println(list.getElem(1));
	
		list.showall();

	}
}

这里写图片描述

你可能感兴趣的:(java数据结构,java,数据结构,双向链表)