链表的循环很重要,基本贯穿所有操作。
1、链表的移动
2、链表尾部特征
单链表类:
public class Link {
public Node head;
public Link() {
head = new Node();
}
/**
* 增加节点
* @param name
*/
public void addNode(String name) {
Node p = head;
//向后遍历
while (p.next != null) {
p = p.next;
}
//p.next == null 增加节点且tail节点指向null
p.next = new Node(name,null);
}
/**
* 删除节点
* @param name
* @return
*/
public boolean delNode(String name) {
Node p = head;
//向后遍历
while (p.next != null) {
//找到需要删除的节点
if(p.next.name.equals(name)) {
p.next = p.next.next;
return true;
}else {
//不是需要删除的节点则继续向后遍历
p = p.next;
}
}
return false;
}
public boolean insertNode(String data,String name) {
Node p = head;
while (p.next != null) {
if(p.next.name.equals(data)) {
//在data节点前插入
// p.next = new Node(name,p.next);
//在data节点后插入
p.next.next = new Node(name,p.next.next);
return true;
}else {
p = p.next;
}
}
return false;
}
public void display() {
Node p = head;
while (p.next != null) {
System.out.println(p.next.name);
p = p.next;
}
}
}
节点类:
public class Node {
public String name;
public Node next;
public Node(String name, Node next) {
this.name = name;
this.next = next;
}
public Node() {
this.next = null;
}
}
测试代码:
Link link = new Link();
link.addNode("1");
link.addNode("2");
link.addNode("3");
link.addNode("4");
link.delNode("2");
link.insertNode("4","5");
link.display();