链表的java实现
链表是一种物理结构上的非连续,非顺序的存储结构,数据元素的逻辑顺序是通过链表中的引用链接次序实现的。
对于单项不带头的非循环链表来说,下面是它的结构图。
下面是对这种链表的 头插、尾插和按照指定位置插入
public class MyLinkedList{
//内部类
class Node{
private int data;
private Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
private Node head;
public MyLinkedList() {
this.head = null;
}
//头插法
public void addFirst(int data) {
Node node=new Node(data);
if (this.head==null){
this.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 (this.head==null){
this.head=node;
}else{
while(cur.next!=null){
cur=cur.next;
}
cur.next=node;
}
}
//按照坐标进行插入
private Node search(int index){
checkIndex(index);
int count=0;
Node cur=this.head;
for (int i = 0; i <index-1 ; i++) {
cur=cur.next;
count++;
}
return cur;
}
private void checkIndex(int index){
if (index<0||index>getLength()){
throw new UnsupportedOperationException("位置不合法");
}
}
public boolean addIndex(int index, int data) {
if (index==0){
addFirst(data);
return true;
}
Node node=new Node(data);
Node cur=search(index);
node.next=cur.next;
cur.next=node;
return false;
}
下面是对头插、尾插、按照指定位置插入的一个测试实现
public class TestLinkedList {
public static void main(String[] args) {
MyLinkedList myLinkedList=new MyLinkedList();
myLinkedList.addFirst(1);
myLinkedList.addFirst(2);
myLinkedList.addFirst(3);
myLinkedList.addFirst(4);
myLinkedList.display();
myLinkedList.addLast(4);
myLinkedList.addLast(3);
myLinkedList.addLast(2);
myLinkedList.addLast(1);
myLinkedList.display();
myLinkedList.addIndex(0,0);
myLinkedList.addIndex(1,1);
myLinkedList.display();
}
}
下面是其结果: