双向链表实现——Java语言版

对于双链表,每个节点既有前驱节点又有后继节点,在某些应用方面更加方便,对于其插入和删除需要修改两个指针,其实现的Java代码如下:

package datastructure;

public class DLLNode {
	private int data;
	private DLLNode next;
	private DLLNode previous;
	public int getData() {
		return data;
	}
	public void setData(int data) {
		this.data = data;
	}
	public DLLNode getNext() {
		return next;
	}
	public void setNext(DLLNode next) {
		this.next = next;
	}
	public DLLNode getPrevious() {
		return previous;
	}
	public void setPrevious(DLLNode previous) {
		this.previous = previous;
	}
	int DLLLength(DLLNode headnode) {
		int length=0;
		DLLNode currentnode = headnode;
		while(currentnode != null) {
			length++;
			currentnode=currentnode.getNext();
		}
		return length;
	}
	DLLNode DLLInsert(DLLNode headnode, DLLNode nodeToInsert, int position) {
		if(headnode == null) {
			return nodeToInsert;
		}
		int size =DLLLength(headnode);
		if(position > size+1 || position < 1) {
			System.out.println("positon of node to insert is invalid. The valid inputs are 1 to "+(size + 1));
			return headnode;
		}
		if(position == 1) {
			nodeToInsert.setNext(headnode);
			headnode.setPrevious(nodeToInsert);
			return nodeToInsert;
		}else {
			DLLNode previousNode = headnode;
			int count =1;
			while(count < position -1) {
				previousNode=previousNode.getNext();
				count++;
			}
			DLLNode currentNode = previousNode.getNext();
			nodeToInsert.setNext(currentNode);
			if(currentNode != null) {
				currentNode.setPrevious(nodeToInsert);
			}
			previousNode.setNext(nodeToInsert);
			nodeToInsert.setPrevious(previousNode);
		}
		return headnode;
	}
	DLLNode DLLDelete(DLLNode headnode, int position) {
		int size =DLLLength(headnode);
		if(position > size+1 || position < 1) {
			System.out.println("positon of node to insert is invalid. The valid inputs are 1 to "+(size + 1));
			return headnode;
		}
		if(position == 1) {
			DLLNode currentNode = headnode.getNext();
			headnode = null;
			currentNode.setPrevious(null);
			return currentNode;
		}else {
			DLLNode perviousNode = headnode;
			int count = 1;
			while(count < position -1) {
				perviousNode = perviousNode.getNext();
				count++;
			}
			DLLNode currentNode = perviousNode.getNext();
			DLLNode laterNode = currentNode.getNext();
			perviousNode.setNext(laterNode);
			if(laterNode != null) {
				laterNode.setPrevious(perviousNode);
				currentNode=null;
			}
			return headnode;
		}
	}
}
双向链表的插入和删除稍微麻烦一点,代码如上!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值