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

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

链表的建立:

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&¤t.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

}

}

相关推荐