1.带头结点的单链表之描述
带头结点的单链表是指,在单链表的第一个结点之前增加一个特殊的结点,称为头结点。头结点的作用就是让所有的链表(包括空链表)的头指针非空,并使对单链表的插入、删除操作不需要区分是否为空表或者是否在第一个位置进行,也就是说,与在其他位置的插入和删除操作一致。
2.java实现
package linearList;
public class HSLinkedList<E> implements LList<E> {
protected Node<E> head;//头指针,指向单链表的头结点
protected Node<E> rear;//尾指针,指向单链表最后一个结点
protected int n;//单链表长度
/*
* 构造空单链表
*/
public HSLinkedList(){
this.head = new Node<E>(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<E> p = this.head;
while(p.next!=null&&i<index){
p = p.next;
i++;
}
Node<E> 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<E> p = this.head;
while(p.next!=null&&i<index){
p = p.next;
i++;
}
if(p.next!=null){
old = (E)p.next.data;
if(p.next==this.rear){
this.rear = p;
}
p.next = p.next.next;//删除p的后继结点
this.n--;
}
}
return old;
}
/*
* 清空单链表
*/
public void clear(){
this.head.next = null;
this.rear = this.head;
this.n = 0;
}
}
3.分析
本次采用变量n和尾指针rear,使得返回单链表的长度和在单链表尾插入时,时间复杂度有原来的O(n)变成了O(1),显著的提升了效率。
4563

被折叠的 条评论
为什么被折叠?



