内存指向长这样
不明白为啥反过来写就不对
public class linkedListDemo {
// 链表测试类
public static void main(String[] args) {
linkedList linkedList = new linkedList();
Node node1 = new Node(1,"狗狗");
Node node2 = new Node(2,"狗狗");
Node node3 = new Node(3,"狗狗");
Node node4 = new Node(100,"狗狗");
Node node5 = new Node(4,"狗狗");
Node node6 = new Node(4,"狗狗1");
linkedList.addByNo(node1);
linkedList.addByNo(node2);
linkedList.addByNo(node3);
linkedList.addByNo(node4);
linkedList.addByNo(node5);
linkedList.addByNo(node6);
linkedList.list();
}
}
//链表类
class linkedList{
private Node head = new Node(0,"");
public void add(Node node){
//找到最末端的值才能添加
Node temp = head;
while(true){
if(temp.next==null){
break;
}
temp=temp.next;
}
temp.next=node;
}
public void addByNo(Node node){
Node temp =head;
//找no大于自己no的地方插入
while(true){
if(temp.next == null){
break;
}
if(temp.next.no>node.no){
break;
}
if(temp.no==node.no){
System.out.println("请勿输入重复编号!");
return;//为什么不能打印出来呀
}
temp=temp.next;
}
node.next=temp.next;//这两句话写反了不行但我不知道为啥
temp.next=node;//写反了啥也答不出来俺不懂
}
public void list(){
if(head.next==null){
System.out.println("链表为空");
return;
}
Node temp = head.next;
while(true){
if(temp == null){
break;//最开始我写temp.next==null那样子就打印不出来最后一个啦
}
System.out.println(temp);
temp=temp.next;
}
}
}
//节点类
class Node{
public Node next;
public int no;
public String name;
public Node(int no,String name){
this.no=no;
this.name=name;
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
", name='" + name + ''' +
'}';
}
}
剩下的明天再写



