带头结点的单链表

         1.带头结点的单链表之描述

                   带头结点的单链表是指,在单链表的第一个结点之前增加一个特殊的结点,称为头结点。头结点的作用就是让所有的链表(包括空链表)的头指针非空,并使对单链表的插入、删除操作不需要区分是否为空表或者是否在第一个位置进行,也就是说,与在其他位置的插入和删除操作一致。

        2.java实现

package linearList;

public class HSLinkedList implements LList {
	protected Node head;//头指针,指向单链表的头结点
	protected Node rear;//尾指针,指向单链表最后一个结点
	protected int n;//单链表长度
	
	/*
	 * 构造空单链表
	 */
	public HSLinkedList(){
		this.head = new Node(null);//创建头结点
		this.head = this.rear;//表明是空单链表
		this.n = 0;
	}
	
	/*
	 * 判断单链表是否为空
	 */
	public boolean isEmpty(){
		return this.head.next == null;
	}
	
	/*
	 * 返回单链表长度
	 */
	public int length(){
		return this.n;
	}
	
	/*
	 * 方法体略,详见单链表类
	 */
	public E get(int index){return null;}
	public E set(int index,E element){return null;}
	public String toString(){return null;}
	
	/*
	 * 在单链表最后插入element对象
	 */
	public boolean add(E element){
		if(element==null){
			return false;
		}else{
			this.rear.next = new Node(element);//尾插入
			this.rear = this.rear.next;//移动尾指针
			this.n++;
		}
		return true;
	}
	
	/*
	 * 插入element对象,插入位置序号为index
	 */
	public boolean add(int index,E element){
		if(element==null){
			return false;
		}else if(index>=this.n){
			return this.add(element);//尾插入
		}else{
			int i = 0;
			Node p = this.head;
			while(p.next!=null&&i q = new Node(element,p.next);//将q结点插入在p结点之后
			p.next = q;
			this.n++;
		}
		return true;
	}
	
	/*
	 * 移除序号为index的对象,返回被移除的对象
	 */
	public E remove(int index){
		E old = null;
		if(index>=0){
			int i = 0;
			Node p = this.head;
			while(p.next!=null&&i
          3.分析

                   本次采用变量n和尾指针rear,使得返回单链表的长度和在单链表尾插入时,时间复杂度有原来的O(n)变成了O(1),显著的提升了效率。

你可能感兴趣的:(数据结构与算法)