首先说一个自己在复习链表时候遇到的难点,头结点和头指针的概念:
头指针:我们把链表中第一个节点的存储位置叫头指针;在我理解,何为头指针,其实就是存储了头结点或者首元结点的位置,在C中称为指向什么的指针,在Java中,就是代表了一个引用,标记了内存地址;假如我理解错了还请指正
头结点,为了操作起来方便,我们在链表中附设了一个节点,这个节点的数据域为空或者可以为一些属性,指针域指向首元结点;
下面贴代码;
首先定义一个list
public interface MyList {
//获得线性表长度
public int size();
//判断线性表是否为空
public boolean isEmpty();
//插入元素
public void insert(int index, Object obj) throws Exception;
//删除元素
public void delete(int index) throws Exception;
//获取指定位置的元素
public Object get(int index) throws Exception;
}
然后是Node
public class Node {
Object element;
Node next;
/**
* 头结点的构造方法 头结点data域为空,指针域指向下一个
*/
public Node(Node next) {
this.next = next;
}
// 非头结点的构造方法
public Node(Object obj, Node nextval) {
this.element = obj;
this.next = nextval;
}
// 获得当前结点的指针域
public Node getNext() {
return this.next;
}
// 获得当前结点数据域的值
public Object getElement() {
return this.element;
}
// 设置当前结点的指针域
public void setNext(Node nextval) {
this.next = nextval;
}
// 设置当前结点数据域的值
public void setElement(Object obj) {
this.element = obj;
}
public String toString() {
return this.element.toString();
}
public void toArray() {
if (this.next == null) {
System.out.println(this.element);
}
this.next.toArray();
}
}
链表实现:
public class MyLinkListimplements MyList {
// 不带头结点的单链表为空时,头指针值为空
// 带头结点的单链表为空,头结点的指针域为空
Node head;// 头指针
intsize;// 当前链表元素个数
Node current;// 当前节点
// 初始化一个空链表
public MyLinkList() {
// 初始化头结点,让头指针指向头结点。并且让当前结点对象等于头结点。
this.head =current = new Node(null);
this.size = 0;
}
// 定位函数,可以用来当删除某个元素时候,获取操作对象的前一个结点,也就是让当前结点对象定位到要操作结点的前一个结点。
// 比如我们要在a2这个节点之前进行插入操作,那就先要把当前节点对象定位到a1这个节点,然后修改a1节点的指针域
public void index(int index) throws Exception {
// 首元结点坐标是0,那么头结点坐标是-1
if (index < -1 ||index > size) {
throw new Exception("异常");
}
// 说明在头结点之后操作。这个地方假如忘记了就会导致初始化的current被下面current=head.next重新置空了,继续执行会有空指针错误
if (index == -1)// 因为第一个数据元素结点的下标是0,那么头结点的下标自然就是-1了。
return;
// 获取头结点
current =head.next;
int i = 0;
while (current !=null && i <index) {
current =current.next;
i++;
}
}
@Override
public Object get(intindex) throws Exception {
if (isEmpty()) {
returnnull;
}
index(index);
return current.getElement();
}
/**
* 删除就是获取前一个节点然后将前一个节点的指针域指向待删节点的下一个节点
*/
@Override
public void delete(int index) throws Exception {
if (isEmpty()) {
throw new Exception("当前链表为空");
}
// 首元结点坐标是0,那么头结点坐标是-1
if (index < -1 ||index > size) {
throw new Exception("异常");
}
index(index - 1);
current.setNext(current.next.next);
size--;
};
@Override
public void insert(int index, Object obj) throws Exception {
// 首元结点坐标是0,那么头结点坐标是-1
if (index < 0 ||index > size) {
throw new Exception("参数错误!");
}
index(index - 1);
current.setNext(new Node(obj,current.next));
size++;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public int size() {
returnthis.size;
}