数据结构与算法 双链表

Java数据结构和算法
上一篇主目录 下一篇
package linkedlist;



public class DoubleLinkedListDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		DoubleLinkedList dl=new DoubleLinkedList();
		System.out.println(dl.getLength());
		dl.add(1, 1);
		System.out.println(dl.getLength());
		dl.show();
		dl.add(2, 2);
		dl.add(3, 3);
		dl.add(4, 4);
		dl.show();
		dl.del(3);
		dl.show();
	}

}


class DoubleLinkedListNode{
	public int val;
	public DoubleLinkedListNode pre;
	public DoubleLinkedListNode next;
	public DoubleLinkedListNode(int val) {
		this.val=val;
	}
	public DoubleLinkedListNode() {
		// TODO Auto-generated constructor stub
	}
}

class DoubleLinkedList{
	public DoubleLinkedListNode head;

	public DoubleLinkedList(int val) {
		head=new DoubleLinkedListNode();
		head.val=val;
		head.next=null;
		head.pre=null;
	}
	
	public DoubleLinkedList() {
		// TODO Auto-generated constructor stub
		head=new DoubleLinkedListNode();
	}

	//获取双向链表的长度
	public int getLength() {
		DoubleLinkedListNode p=head.next;
		int length=0;
		while(p!=null) {
			length++;
			p=p.next;
		}
		return length;
	}
	
	//显示双向链表
	public void show() {
		DoubleLinkedListNode p=head.next;
		System.out.print("list:");
		while(p!=null) {
			System.out.printf("%d\t",p.val);
			p=p.next;
		}
		System.out.println();
	}
	
	//在指定位置插入
	public void add(int position,int val) {
		if(position<0||position>getLength()+1) {
			System.out.println("invalid position");
		}else {
			DoubleLinkedListNode p=head;
			for(int i=0;i<position-1;i++) {
				p=p.next;
			}
			DoubleLinkedListNode d=new DoubleLinkedListNode(val);
			if(p.next==null) {
				p.next=d;
				d.pre=p;
			}else {
				p.next.pre=d;
				d.pre=p;
				d.next=p.next;
				p.next=d;
				System.out.println("ok");
			}
			
		}
	}
	
	//删除指定位置的节点
	public void del(int position) {
		
		if(position<=0||position>getLength()) {
			System.out.println("invalid position");
		}else {
			DoubleLinkedListNode p=head;
			for(int i=0;i<position-1;i++) {
				p=p.next;
			}
			p.next.next.pre=p;
			p.next=p.next.next;
			System.out.println("del position:"+position);
		}
	}
	
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值