如何建立链表,链表的建立过程

简介: 如何建立链表,链表的建立过程

链表的建立:

Java中可以使用类来表示链表,每个节点由一个类表示,链表本身由一个包含头节点的类表示。

1、创建节点类

首先,创建一个节点类,该类包含数据和指向下一个节点的引用。

//创建节点类
//创建一个节点类,该类包含数据和指向下一个节点的引用。
public class Node {
    int data;
    Node next;
    
    public Node(int data) {
        this.data=data;
        this.next=null;
    }
}

2、创建链表类

创建一个链表类,该类包含链表的操作方法,如添加节点、删除节点、查找节点等。

public class LinkedList {
    Node head;
    //添加元素
    public void append(int data) {
        Node newNode=new Node(data);
        //判断头结点是否为空,为空直接添加到头结点
        if(head==null) {
            head=newNode;
        }else {//头结点不为空,找到尾结点添加数据
            Node current=head;
            while(current.next!=null) {
                current=current.next;
            }
            current.next=newNode;
        }
    }
    //打印元素
    public void display() {
        Node current=head;
        //按结点顺序依次打印
        while(current!=null) {
            System.out.print(current.data+"->");
            current=current.next;
        }
        System.out.println("null");
    }
    //查找元素
    public boolean search(int target) {
        Node current =head;
        //按结点顺序依次查找,找到返回true,未找到返回false
        while(current!=null) {
            if(current.data==target) {
                return true;
            }
            current=current.next;
        }
        return false;
    }
    //删除元素
    public void remove(int target) {
        //判断删除元素是否为头结点,是的话用头结点的下一元素成为新头结点,原头结点舍弃
        if(head!=null&&head.data==target) {
            head=head.next;
            return;
        }
        //删除元素不为头结点,从头结点往下依次查找
        Node current=head;
        while(current!=null) {
            //当前结点不为空时,确保当前结点的下一节点有值,判断下一结点是否为目标值
            //当下一结点为目标值,将下一结点的内存放的next直接覆盖下一结点,以此丢弃目标结点
            if(current.next!=null&&current.next.data==target) {
                current.next=current.next.next;
                return;
            }
            current=current.next;
        }
        //查找到最后未发现目标元素
        System.out.println("没有该元素");
    }
}

删除结点:

3、链表的使用:

对链表进行插入、打印、删除操作:

public class Test {
    public static void main(String[] args) {
        LinkedList linkedList=new LinkedList();
        //添加四个结点
        linkedList.append(1);
        linkedList.append(2);
        linkedList.append(3);
        linkedList.append(4);
        linkedList.display();//1->2->3->4->null
        //查找3这个结点,存在返回true
        System.out.println(linkedList.search(3));
        //删除3这个结点
        linkedList.remove(3);
        linkedList.display();//1->2->4->null
    }
}
相关文章
|
5天前
|
存储 C语言
建立简单的静态链表
建立简单的静态链表
12 1
|
5天前
|
存储
数据结构实验之链表一:顺序建立链表
数据结构实验之链表一:顺序建立链表
|
5天前
尾插法建立链表
尾插法建立链表
5 0
尾插法建立链表
|
5天前
|
存储 C语言
建立动态链表
建立动态链表
13 1
|
5天前
|
存储 缓存 算法
双向链表的建立和使用场景
双向链表的建立和使用场景
|
5天前
连接两个链表
连接两个链表。
27 7
|
7月前
|
C++
C/C++之链表的建立
C/C++之链表的建立
45 0
|
9月前
6-10 建立学生信息链表(20分)
本题要求实现一个将输入的学生成绩组织成单向链表的简单函数。
70 0
|
存储
大话数据结构--二叉树建立及结构实现
大话数据结构--二叉树建立及结构实现
58 0
|
算法
深度解析带头节点单链表的增删改查与销毁链表等操作(含算法编写步骤,有完整代码)
深度解析带头节点单链表的增删改查与销毁链表等操作(含算法编写步骤,有完整代码)