已经有了数组了,为什么还需要链表?
数组的增删改查操作比较麻烦,且内存地址必须连续,限制较多
而链表可以实现内存地址不连续,且使增删改查更加便捷
下面定义一个节点类Node
public class Node {
Integer val; //用于保存一个节点的值
Node next; //用来保存下一个节点的地址值,类型是Node,因为其他节点的类型也是Node,只有用Node类型才能储存Node类型的地址
public Node(Integer val){
this.val=val;
}
}
定义一个测试类
public class Test {
public static void main(String[] args) {
Node node1 = new Node(5);
Node node2 = new Node(7);
Node node3 = new Node(4);
Node node4 = new Node(2);
Node node5 = new Node(0);
}
}
这样一个链表就构成了
但是这样的链表并不能满足我们的需求
所以我们定义一个链表类
public class LinkList {
//定义头节点
Node head = null;
//尾插法,从链表的尾部插入数据
public void insert(Integer val){
//通过方法的参数创建一个节点对象
Node node = new Node(val);
//判断头节点是否为空
if (head == null){
head = node;
return;
}
//定义一个用于检索的指针,从头部开始
Node indexNode = head;
//从头开始遍历,找到指向null的节点(尾部)
while (indexNode.next != null){
indexNode = indexNode.next;
}
//找到后利用检索指针的.next区域将node添加到尾部
indexNode.next = node;
}
public void headInsert(Integer val){
//通过方法的参数创建一个节点对象
Node node = new Node(val);
//判断头节点是否为空
if (head == null){
head = node;
return;
}
node.next=head;
head=node;
}
public void printList(){
Node indexNode = head;
String string = "[";
while (indexNode.next != null){
string += (indexNode.val+",");
indexNode = indexNode.next;
}
string += (indexNode.val+"]");
System.out.println(string);
}
public int getLength(){
int length = 0;
Node indexNode = head;
while (indexNode != null){
length++;
indexNode = indexNode.next;
}
return length;
}
public boolean contains(int val){
Node indexNode = head;
while (indexNode != null){
if (indexNode.val==val){
return true;
}
indexNode = indexNode.next;
}
return false;
}
public void addNodeAtIndex(int val,int index){
if(index == 0){
headInsert(val);
}else if (index ==getLength()){
insert(val);
}else{
Node node = new Node(val);
Node indexNode = head;
Node tempNode = null;
int position = 0;
while (indexNode != null){
if (position == index){
node.next = indexNode;
tempNode.next = node;
return;
}
tempNode = indexNode;
indexNode = indexNode.next;
position++;
}
}
}
public void delNodeAtIndex(int index){
if(index == 0){
head = head.next;
}else{
int position = 0;
Node indexNode = head;
while (indexNode != null){
if (position == index-1){
System.out.println("删除成功,被删除的元素是:"+indexNode.next.val);
indexNode.next=indexNode.next.next;
return;
}
indexNode = indexNode.next;
position++;
}
}
}
}
这个类里面已经写好了链表的增删改查方法
改写一遍测试类
public class Test {
public static void main(String[] args) {
LinkList linkList = new LinkList();
linkList.insert(5);
linkList.insert(7);
linkList.insert(4);
linkList.insert(2);
linkList.headInsert(0);
linkList.printList();
System.out.println(linkList.contains(2));
System.out.println("链表长度为:"+linkList.getLength());
linkList.delNodeAtIndex(1);
linkList.printList();
System.out.println(linkList.contains(2));
System.out.println("链表长度为:"+linkList.getLength());
}
}
查看输出
这样我们的包含基本增删改查方法的链表就实现了