链表的Java函数实现
发布时间:2023-06-17 08:38:35
Java中链表是一种非常常见的数据结构,通过链接节点来构造一个线性表,具有动态性和扩展性,适合大部分的场景。在Java的实现中,链表可以通过类以及节点来实现,本文将从这两个方面来介绍链表的Java函数实现。
一、类的实现
链表可以用一个节点来表示,但这样比较麻烦,我们可以新建一个类来实现链表。一个链表类应该至少包含以下的内容:
1.一个内部类Node来表示链表的节点;
2.链表的头节点head;
3.链表的长度length。
以下是一个简单的链表类的实现:
public class LinkedList {
private class Node{
int value;
Node next;
Node(int value){
this.value = value;
this.next = null;
}
}
private Node head;
private int length;
//初始化链表
LinkedList(){
head = null;
length = 0;
}
//获取链表长度
public int length(){
return length;
}
//判断链表是否为空
public boolean isEmpty(){
return length == 0;
}
//插入新节点
public void insert(int value){
Node node = new Node(value);
if(head == null){
head = node;
}else{
Node p = head;
while(p.next != null){
p = p.next;
}
p.next = node;
}
length++;
}
//删除节点
public void remove(int value){
if(head == null){
return;
}
if(head.value == value){
head = head.next;
length--;
return;
}else{
Node p = head;
while(p.next != null){
if(p.next.value == value){
p.next = p.next.next;
length--;
return;
}
p = p.next;
}
}
}
//查找节点
public boolean find(int value){
Node p = head;
while(p != null){
if(p.value == value){
return true;
}
p = p.next;
}
return false;
}
//打印链表中的节点
public void print(){
if(head == null){
return;
}
Node p = head;
while(p != null){
System.out.print(p.value + " ");
p = p.next;
}
System.out.println();
}
}
在上述代码中,Node表示链表的节点,其中包括节点的值value和下一个节点的地址next。LinkedList则是链表类,在其中定义了一些常用的函数。其中,insert函数可以在链表末尾加入新节点;remove函数可以删除链表中的指定节点;find函数可以查找链表中的节点;print函数可以输出链表中的所有节点。
二、节点的实现
除了使用类之外,我们也可以直接使用节点的概念来实现链表,LinkedList类将只是一个指向链表头节点的指针。下面是节点类的实现:
public class Node {
int value;
Node next;
public Node(){}
public Node(int value){
this.value = value;
}
public Node(int value, Node next){
this.value = value;
this.next = next;
}
}
在上述代码中,Node表示链表的节点,其中包括节点的值value和下一个节点的地址next。这里有三个构造函数,分别是无参构造函数、带一个参数的构造函数和带两个参数的构造函数。
LinkedList类则只需要实现一些跟链表相关的操作即可,下面是一个简单的LinkedList类实现方式:
public class LinkedList {
Node head;
//初始化链表
public LinkedList(){}
//插入新节点
public void insert(int value){
Node node = new Node(value);
node.next = head;
head = node;
}
//删除节点
public void remove(int value){
if(head.value == value){
head = head.next;
}else{
Node p = head;
while(p.next != null){
if(p.next.value == value){
p.next = p.next.next;
return;
}
p = p.next;
}
}
}
//查找节点
public boolean find(int value){
Node p = head;
while(p != null){
if(p.value == value){
return true;
}
p = p.next;
}
return false;
}
//打印链表中的节点
public void print(){
Node p = head;
while(p != null){
System.out.print(p.value + " ");
p = p.next;
}
System.out.println();
}
}
在上述代码中,LinkedList类中的insert函数在链表的头节点加入一个新节点;remove函数在链表中删除一个节点;find函数在链表中查找一个节点;print函数则用来打印整个链表。
