package com.java.datastructure.lineartable;
// 线性表 - java单链表实现方式
public class SingLinkList {
private Node head;
public SingLinkList() {
head = new Node();
head.next = null;
}
public void addNode(String data) {
Node p = head;
//当前只存在多个元素
while (p.next!=null) {
p = p.next;
}
p.next = new Node(data);
}
public void delNode(String data) {
Node p = head;
if(p.next==null) {
return ;
}
while (p.next!=null) {
if(p.next.getName().equals(data)) {
p.next = p.next.next;
break;
} else {
p = p.next;
}
}
}
public void display(String begContetn) {
Node p = head;
while(p.next!=null) {
System.out.println(begContetn+" Node name :"+p.next.getName());
p = p.next;
}
}
public String findNode(String data) {
Node p = head;
while (p.next!=null) {
if(p.next.getName().equals(data)) {
return data;
} else {
p = p.next;
}
}
return null;
}
public void insertBeforeNode(String befNode, String data) {
Node p = head;
while(p.next!=null) {
if(p.next.getName().equals(befNode)) {
Node temp = p.next;
Node inserData = new Node(data);
inserData.next = temp.next;
temp.next = inserData;
break;
} else {
p = p.next;
}
}
}
static class Node {
private String name;
private Node next;
public Node() {
}
public Node(String name) {
this.name = name;
next = null;
System.out.println("生产节点:" + name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public static void main (String[] args) {
SingLinkList list = new SingLinkList();
list.addNode("hcb1");
list.addNode("hcb2");
list.addNode("hcb3");
list.display("show all");
list.insertBeforeNode("hcb2","hcb2-bef");
list.display("show insert");
list.delNode("hcb2");
list.display("show del");
}
}
3. 线性表 - java单链表实现方式
最新推荐文章于 2021-04-21 16:49:53 发布
本文详细介绍了使用Java实现单链表的数据结构,包括添加、删除、查找和插入节点等核心操作,并提供了完整的代码示例。
1067

被折叠的 条评论
为什么被折叠?



