链表
链表的介绍
链表是有序的列表 链表是以节点的方式来存储,即链式存储 每个节点包含data域(存放数据),next域(指向下一个节点) 如图:链表的各个节点不一定是连续存储的 链表分带头节点的链表和没有头节点的链表(根据实际的需求来确定)
代码实现
public class HeroNode {
public int no;
public String name;
public String neckName;
public HeroNode next;
public HeroNode ( int no, String name, String neckName) {
this . no = no;
this . name = name;
this . neckName = neckName;
}
public HeroNode ( int no) {
this . no = no;
}
@Override
public String toString ( ) {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", neckName='" + neckName + "'}" ;
}
}
public class HeroNode {
public int no;
public String name;
public String neckName;
public HeroNode next;
public HeroNode ( int no, String name, String neckName) {
this . no = no;
this . name = name;
this . neckName = neckName;
}
public HeroNode ( int no) {
this . no = no;
}
@Override
public String toString ( ) {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", neckName='" + neckName + "'}" ;
}
}
链表优化(根据no排序而非添加顺序)
思路分析
首先找到新添加节点的位置,是通过辅助变量(指针) 新的节点.next=temp.next 将temp.next = 新的节点 增加一个修改和删除功能
代码实现
public class SingleLinkedList2 {
private HeroNode head = new HeroNode ( 0 ) ;
public void add ( HeroNode heroNode) {
HeroNode temp = head;
while ( true ) {
if ( temp. next== null) {
break ;
}
temp = temp. next;
}
temp. next = heroNode;
}
public void addByOrder ( HeroNode heroNode) {
HeroNode temp = head;
boolean flag = false ;
while ( true ) {
if ( temp. next== null) {
break ;
}
if ( temp. next. no> heroNode. no) {
break ;
} else if ( temp. next. no == heroNode. no) {
throw new RuntimeException ( heroNode. no+ "编号已经存在" ) ;
}
temp = temp. next;
}
heroNode. next = temp. next;
temp. next = heroNode;
}
public void update ( HeroNode heroNode) {
HeroNode temp = head;
while ( true ) {
if ( temp== null) {
System. out. printf ( "没有%d编号\n" , heroNode. no) ;
return ;
}
if ( temp. no== heroNode. no) {
temp. name= heroNode. name;
temp. neckName = heroNode. neckName;
return ;
}
temp = temp. next;
}
}
public void delete ( int no) {
if ( head. next == null) {
System. out. println ( "链表为空不能删除" ) ;
return ;
}
HeroNode temp = head;
while ( true ) {
if ( temp. next== null) {
System. out. printf ( "没有%d编号,无法删除\n" , no) ;
return ;
}
if ( temp. next. no== no) {
temp. next= temp. next. next;
return ;
}
temp = temp. next;
}
}
public void showList ( ) {
if ( head. next== null) {
System. out. println ( "链表为空" ) ;
return ;
}
HeroNode temp = head. next;
while ( true ) {
if ( temp== null) {
break ;
}
System. out. println ( temp) ;
temp = temp. next;
}
}
}