import org.junit.Test;
import java.util.*;
/**
* @author ztyOperation
* @create 2022-04-05-22:13
*/
public class DoubleLinkedList {
public static void main(String[] args) {
//测试
//增加s
PersonList list = new PersonList();
list.addNodes();
list.showList();
}
}
class PersonList {
private Scanner in = new Scanner(System.in);
private PersonNode head = new PersonNode("");
public PersonNode getHead() {
return head;
}
/**
* 将newNode添加入链表(尾插)
*
* @param newNode 将newNode添加到链表中
*/
public void addNode(PersonNode newNode) {
PersonNode pMove = head;
while (pMove.next != null) {
pMove = pMove.next;
}
pMove.next = newNode;
newNode.pre = pMove;
}
/**
* 打印单链表
*/
public void showList() {
PersonNode pMove;
for (pMove = head.next; pMove != null; pMove = pMove.next) {
if (pMove.next != null) System.out.print(pMove.name + "<->");
else System.out.println(pMove.name);
}
}
/**
* 反向打印单链表
*/
public void reverseShowList() {
PersonNode pMove = head;
while (pMove.next != null) {
pMove = pMove.next;
}
for (; pMove.pre != null; pMove = pMove.pre) {
if (pMove.pre.pre != null) System.out.print(pMove.name + "<->");
else System.out.println(pMove.name);
}
}
/**
* 不断添加结点,直到输入"e"
*/
public void addNodes() {
String str;
System.out.print("请输入姓名(按e退出): ");
PersonNode temp = new PersonNode(str = in.next());
PersonNode pMove = head;
while (!"e".equals(str)) {//字符串不能用!= ,需要用equals
pMove.next = temp;
temp.pre = pMove;
pMove = temp;
System.out.print("请输入姓名(按e退出): ");
temp = new PersonNode(str = in.next());
}
}
/**
* 删除结点
*
* @param name 删除姓名为name的结点
*/
public void deleteNode(String name) {
PersonNode pMove;
if (head.next == null) {//空链表
System.out.println("链表为空");
return;
}
for (pMove = head.next; pMove != null; pMove = pMove.next) {
if (pMove.name.equals(name)) {
if (pMove.next != null) {
pMove.pre.next = pMove.next;
pMove.next.pre = pMove.pre;
} else {
pMove.pre.next = null;
}
break;
}
}
}
/**
* 修改结点
*
* @param name 查询要修改的节点的姓名
* @param newNode 将newNode替换原节点
*/
public void modifyNode(String name, PersonNode newNode) {
PersonNode pMove;
if (head.next == null) {
System.out.println("链表为空");
return;
}
for (pMove = head.next; pMove != null; pMove = pMove.next) {
if (pMove.name.equals(name)) {
//连接前一个结点
pMove.pre.next = newNode;
newNode.pre = pMove.pre;
//连接后一个节点
if (pMove.next != null) {
pMove.next.pre = newNode;
newNode.next = pMove.next;
}else{
//newNode.next = null;可以不要
}
break;
}
}
}
/**
* @param name 要查询结点的姓名
* @return null:查询不到 StuNode : 返回查询到的结点
*/
public PersonNode findNode(String name) {
PersonNode pMove;
if (head.next == null) {
System.out.println("链表为空");
return null;
}
for (pMove = head.next; pMove != null; pMove = pMove.next) {
if (pMove.name.equals(name)) {
return pMove;
}
}
return null;
}
}
class PersonNode {
public String name;
PersonNode next;
PersonNode pre;
public PersonNode(String name) {
this.name = name;
}
@Override
public String toString() {
return "name : " + name;
}
}
双链表的增删改查
最新推荐文章于 2023-03-17 20:49:29 发布