数据结构JavaScript——双向链表、双向循环链表

关于链表简介、单链表、单向循环链表、JS中的使用以及扩充方法:  单链表、循环链表的JS实现

关于四种链表的完整封装: https://github.com/zhuwq585/Data-Structure-in-JavaScript/blob/master/LinkedList.js


双向链表:单向链表只能向着一个方向遍历链表节点,而在节点指针域中增加了前向指针的双向链表,则可以向着两个方向遍历节点。这使得双向链表也可以在任何一个节点遍历整个链表。

function DoublyLinkedList() {
	var Node = function(element) {
		this.element = element;
		this.next = null;
		this.prev = null;
	};

	var length = 0,
		head = null,
		tail = null;

	this.append = function(element){
		var node = Node(element),
		    current,
		    previous;
		
		if(!head){
			head = node;
			tail = node;
		}else{
			current = head;
			while(current){
				previous = current;
				current = current.next;
			}

			node.next = current;
			current.prev = node;
			previous.next = node;
			node.prev = previous;
		}

		length++;
		return true;
	}

	this.insert = function(position,element){
		if(position > -1 && position < length){
			var node = new Node(element),
			    current = head,
			    previous,
			    index = 0;

			if(position === 0){

				if(!head){
					head = node;
					tail = node;
				}else{
					node.next = current;
					current.prev = node;
					head = node;
				}

			}else if (position === length -1){
				current = tail;
				current.next = node;
				node.prev = cur
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值