JAVA实现单向链表的增删操作

来源:互联网 发布:hfss微带线端口 编辑:程序博客网 时间:2024/06/01 13:39

概念:单向链表(单链表)是链表的一种,其特点是链表的链接方向是单向的,对链表的访问要通过顺序读取从头部开始;链表是使用指针进行构造的列表;又称为结点列表,因为链表是由一个个结点组装起来的;其中每个结点都有指针成员变量指向列表中的下一个结点;列表是由结点构成,head指针指向第一个成为表头结点,而终止于最后一个指向nuLL的指针。



节点类,用来存储该节点信息和下一个节点对象。

public class Node { // 保存每一个节点public String data; // 节点的内容public Node next; // 保存下一个节点public Node(String data) { // 通过构造方法保存节点内容this.data = data;}public void add(Node node) { // 增加节点if (this.next == null) { // 如果下一个节点为空,则把新节点加入到next的位置上this.next = node;} else { // 如果下一个节点不为空,则继续找nextthis.next.add(node);}}public void print() { // 打印节点if (this.next != null) {System.out.print(this.data + "-->");this.next.print();} else {System.out.print(this.data + "\n");}}public boolean search(String data) { // 内部搜索节点的方法if (this.data.equals(data)) {return true;}if (this.next != null) {return this.next.search(data);} else {return false;}}public void delete(Node previous, String data) { // 内部删除节点的方法if (this.data.equals(data)) {previous.next = this.next;} else {if (this.next != null) {this.next.delete(this, data);}}}}


链表类 提供操作链表的方法

public class Link {private Node root; // 定义头节点public void addNode(String data) { // 根据内容添加节点Node newNode = new Node(data); // 要插入的节点if (this.root == null) { // 没有头节点,则要插入的节点为头节点this.root = newNode;} else { // 如果有头节点,则调用节点类的方法自动增加this.root.add(newNode);}}public void print() { // 展示列表的方法if (root != null) { // 当链表存在节点的时候进行展示this.root.print();}}public boolean searchNode(String data) { // 在链表中寻找指定内容的节点return root.search(data); // 调用内部搜索节点的方法}public void deleteNode(String data) { // 在链表中删除指定内容的节点if (root.data.equals(data)) { // 如果是头节点if (root.next != null) {root = root.next;} else {root = null;}} else {root.next.delete(this.root, data);}}}


操作链表进行增删查

public class LinkDemo {public static void main(String[] args) {Link l = new Link();l.addNode("A");l.addNode("B");l.addNode("C");l.addNode("D");System.out.println("原链表:");l.print();String searchNode = "B";System.out.println("查找节点:" + searchNode);String result = l.searchNode(searchNode) ? "找到!" : "没找到!";System.out.println("查找结果:" + result);System.out.println("删除节点:" + searchNode);l.deleteNode(searchNode);System.out.println("删除节点后的链表:");l.print();}}



原创粉丝点击