package com. atguigu. linkedlist;
public class SingleLinkedListDemo { public static void main ( String[ ] args) { HeroNode hearo1 = new HeroNode ( 1 , "宋江" , "及时雨" ) ; HeroNode hearo2 = new HeroNode ( 2 , "卢俊义" , "玉麒麟" ) ; HeroNode hearo3 = new HeroNode ( 3 , "吴用" , "智多星" ) ; HeroNode hearo4 = new HeroNode ( 4 , "林冲" , "及时钉钉雨" ) ; SingleLinkedList singleLinkedList = new SingleLinkedList ( ) ;
singleLinkedList. addByOrder ( hearo1) ; singleLinkedList. addByOrder ( hearo4) ; singleLinkedList. addByOrder ( hearo2) ; singleLinkedList. addByOrder ( hearo3) ; singleLinkedList. list ( ) ; }
}
class SingleLinkedList { 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) { flag= true ; break ; } temp= temp. next; } if ( flag) { System. out. println ( "准备插入的英雄的编号" + heroNode. no+ "已经存在了,不能加入" ) ; } else { heroNode. next= temp. next; temp. next= heroNode; } } public void list ( ) { if ( head. next== null) { System. out. println ( "链表为空" ) ; return ; } HeroNode temp= head. next; while ( true ) { if ( temp== null) { break ; } System. out. println ( temp. toString ( ) ) ; temp= temp. next; } } }
class HeroNode { public int no; public String name; public String nickname; public HeroNode next; public HeroNode ( int no, String name, String nickname) { this . no= no; this . name= name; this . nickname= nickname; } @Override public String toString ( ) { return "HeroNode{" + "no=" + no + ", name='" + name + '\'' + ", nickname='" + nickname + '\'' +
'}' ; }
}