public class LinkedDemo {
private static class Node{
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
//头指针
private Node head;
//尾指针
private Node last;
//链表的长度
private int size;
/**
* 链表的插入
* @param data 要插入的数据
* @param index 要插入的位置
*/
public void insertList(int data,int index){
if (index<0||index>size){
throw new ArrayIndexOutOfBoundsException("链表越界,检查长度");
}
Node insertNode = new Node(data);
if (size==0){
//长度为0,头部插入
head=insertNode;
last=insertNode;
}else if (index==size){
//插入尾部
last.next=insertNode;
last=insertNode;
}else {
//插入中间
Node preNode=getNode(index-1);
Node nextNode=preNode.next;
insertNode.next=nextNode;
preNode.next=insertNode;
}
size++;
}
/**
* 获取链表的一个节点
* @param index 要获取节点的位置
* @return Node
*/
private Node getNode(int index) {
if (size==0||index>size){
throw new ArrayIndexOutOfBoundsException("链表越界,检查长度");
}
Node temp = head;
for (int i=0;i<index;i++){
temp=temp.next;
}
size--;
return temp;
}
private void output(){
Node temp = head;
while (temp!=null){
int data = temp.data;
System.out.println(data+"");
temp = temp.next;
}
}
public static void main(String[] args) {
LinkedDemo l = new LinkedDemo();
l.insertList(1,0);
l.insertList(2,1);
l.insertList(3,2);
l.insertList(4,2);
l.output();
}
}
数据结构-链表
最新推荐文章于 2024-08-13 14:59:01 发布