链表
链表是一种物理存储结构上非连续存储结构,数据元素的逻辑顺序是通过链表中的引用链接次序实现的 。
实际中链表的结构非常多样,以下情况组合起来就有8种链表结构:
- 单向、双向
- 带头、不带头
- 循环、非循环
无头单向非循环链表
结构简单,一般不会单独用来存数据。实际中更多是作为其他数据结构的子结构,如哈希桶、图的邻接表等等。
实现无头单向非循环链表
class Node{
public int data;
public Node next;
public Node(int data){
this.data = data;
}
}
public class MySingleList {
public Node head;
//头插法
public void addFirst(int data){
Node node = new Node(data);
if (this.head == null){
head = node;
}else{
node.next = this.head;
this.head = node;
}
}
//尾插法
public void addLast(int data){
Node node = new Node(data);
Node cur = this.head;
if(cur == null){
this.head = node;
return;
}
while(cur.next != null){
cur = cur.next;
}
cur.next = node;
}
//任意位置插入,第一个数据节点为0号下标
public boolean addIndex(int index,int data){
if (index < 0 || index > size() ){
System.out.println("index不合法");
return false;
}
if (index == 0){
addFirst(data);
return true;
}
Node node = new Node(data);
//找到插入节点位置的前一个节点
Node re = searchPrve(index);
node.next = re.next;
re.next = node;
return true;
}
//找到插入节点位置的前一个节点
public Node searchPrve(int index){
int count = 0;
Node cur = this.head;
while (count < index-1){
cur = cur.next;
count++;
}
ret