第六章(链表)

1,单向链表里每个节点至少有两个属性,值和指针,链表必须有头结节点(head);

2,插入和删除新节点时要知道其前的节点位置;

3,双向链表是多了一个前继指针;

4,循环链表是初始时头节点指向头节点而不是指向null,总是头节点的前一个节点指向头节点。

	//节点信息
			function Node(element){
				this.element=element;
				this.next=null;
			}
			//创建链表的时候必须得有表头
			function LList(){
				this.head=new Node("head");
				this.find=find;
				this.insert=insert;
				this.remove=remove;
				this.findPrevious=findPrevious;
				this.display=display;
				this.currentNode=this.head;//当前节点默认为head
				this.show=show;
				this.advance=advance;
			}
			//查找,每次都是重头开始查找
			function find(item){
				var currNode=this.head;
//				console.log(currNode.element);
				while(currNode.element !=item){
					currNode=currNode.next;
				}
				return currNode;
			}
			//插入
			function insert(newElement,item){
				var newNode=new Node(newElement);
				var current=this.find(item);
				newNode.next=current.next;
				current.next=newNode;
			}
			//删除链表中的一个节点,得先找到该节点的前驱
			function findPrevious(item){
				var currNode=this.head;
				while (!(currNode.next==null)&&(currNode.next.element!=item)){
					currNode=currNode.next;					
				}
				return currNode;
			}
			//删除节点
			function remove(item){
				var prevNode=this.findPrevious(item);
				if(!(prevNode.next==null)){
					prevNode.next=prevNode.next.next;
				}
			}
			//显示链表内容
			function display(){
				var currNode=this.head;
				while (!(currNode.next==null)){
					console.log(currNode.next.element);
					currNode=currNode.next;
				}
			}
			//当前节点向后移动n个节点
			function advance(n){
				while(!(this.currentNode.next==null)&&n!=0){
					this.currentNode=this.currentNode.next;
				}
				return this.currentNode;
			}
			//显示当前节点
			function show(){
				console.log(this.currentNode.element);
			}
			//主程序
			var  cities=new LList();
			cities.insert("Xi'an","head");
			cities.insert("shanghai","Xi'an");
			cities.insert("guangzhou","shanghai");
			cities.display();
			
			cities.remove("shanghai");
			cities.display();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值