单项链表的创建
1.创建单链表
代码如下(示例):
/**
* 单链表实现
*/
public class LinkList {
public static void main(String[] args) {
LinkedList<Object> linkedList = new LinkedList<>();
linkedList.add(1);
linkedList.add(12);
linkedList.add(13);
System.out.println(linkedList.getFirst());
HeroNode heroNode = new HeroNode(1, "宋江", "宋江");
HeroNode heroNode1 = new HeroNode(8, "李白", "李白");
HeroNode heroNode2 = new HeroNode(3, "刘备", "刘备");
HeroNode heroNode3 = new HeroNode(4, "林冲", "林冲");
SingleLinkeList singleLinkeList = new SingleLinkeList();
// singleLinkeList.add(heroNode);
// singleLinkeList.add(heroNode1);
// singleLinkeList.add(heroNode2);
// singleLinkeList.add(heroNode3);
singleLinkeList.addByOrder(heroNode);
singleLinkeList.addByOrder(heroNode1);
singleLinkeList.addByOrder(heroNode2);
singleLinkeList.addByOrder(heroNode3);
//遍历
singleLinkeList.list();
}
}
//定义 单链表 管理
class SingleLinkeList{
//先初始化一个头节点
private HeroNode head =new HeroNode(0,"","");
//添加节点到单链表
//思路 当不考虑编号顺序时
//找到当前节点的最后一个节点
//将最后这个节点的next指向新的节点
public void add(HeroNode heroNode)
{
//因为头节点不能动我们需要一个辅助遍历
HeroNode temp = head;
//遍历找到最后
while (true)
{
if(temp.next==null)
{
break;
}
//如果没有找,到就将temp后移
temp=temp.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);
//将next后移
temp = temp.next;
}
}
public void addByOrder(HeroNode heroNode)
{
HeroNode temp = head;
boolean flag = false;
while (true)
{
if(temp.next == null)
{
break;
}else 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("ycz");
}else {
heroNode.next=temp.next;
temp.next=heroNode;
}
}
}
//1定义一个HeroNode,每一个HeroNode就是一个节点
class HeroNode{
public int no;
public String name;
public String nikename;
public HeroNode next;//纸箱下一个节点
//构造器
public HeroNode(int no, String name, String nikename) {
this.no = no;
this.name = name;
this.nikename = nikename;
}
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", nikename='" + nikename + '\'' +
'}';
}
}