单链表
采用头结点的方式创建单链表
1.添加数据
正确写法:
public void addNode(HeroNode node){
HeroNode supNeedle = head;
while(supNeedle.next != null){
supNeedle = supNeedle.next;
}
supNeedle.next = node;
}
错误写法1:
报错原因:如果初始链表只有头结点,那么supNode.next会指向未知位置
public void addNode(HeroNode node){
HeroNode supNeedle = head.next;
while(supNeedle != null){
supNeedle = supNeedle.next;
}
supNeedle.next = node;
}
错误写法2:
报错原因:supNode仅仅是一个指针,试图把节点赋给指针变量是行不通的
public void addNode(HeroNode node){
HeroNode supNeedle = head.next;
while(supNeedle != null){
supNeedle = supNeedle.next;
}
supNeedle = node;
}
2.查看链表
public void showLinkList(){
if(head.next == null){
System.out.println("链表为空");
return;
}
HeroNode supNeedle = head.next;
while(supNeedle != null){
System.out.println(supNeedle);
supNeedle = supNeedle.next;
}
}
3.小结
-
supNeedle是指针域,指向下一个节点 → -
在addNode方法中,从头结点出发
HeadNode temp = head;
while(temp.next != null){
temp = temp.next;
}
-
在showLinkList方法中,从有效节点开始 HeadNode temp = head.next;
while(temp != null){
System.out.println(temp);
temp = temp.next;
}
4.完整代码 package clwAhu;
public class DLB {
public static void main(String[] args) {
HeroNode hero1 = new HeroNode(1,"张三","端茶","倒水");
HeroNode hero2 = new HeroNode(2,"李四","敲锣","打鼓");
HeroNode hero3 = new HeroNode(3,"王五","放火","烧山");
SingLinkList singLinkList = new SingLinkList();
singLinkList.addNode(hero1);
singLinkList.addNode(hero2);
singLinkList.addNode(hero3);
singLinkList.showLinkList();
}
}
class SingLinkList{
private final HeroNode head = new HeroNode(0,"","","");
public void addNode(HeroNode node){
HeroNode supNode = head;
while (supNode.next != null) {
supNode = supNode.next;
}
supNode.next = node;
}
public void showLinkList(){
if(head.next == null){
System.out.println("链表为空");
return;
}
HeroNode supNode = head.next;
while (supNode != null) {
System.out.println(supNode);
supNode = supNode.next;
}
}
}
class HeroNode{
public int no;
public String name;
public String skill_q;
public String skill_w;
public HeroNode next;
public HeroNode(int no, String name, String skill_q, String skill_w) {
this.no = no;
this.name = name;
this.skill_q = skill_q;
this.skill_w = skill_w;
}
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", skill_q='" + skill_q + '\'' +
", skill_w='" + skill_w + '\'' +
'}';
}
}
|