标签:als break 存在 boolean null 删除 return demo method
/**
* 带头结点的单链表
*/
public class LinkListDemo {
public static void main(String[] args){
Node n1 = new Node(1,"A");
Node n2 = new Node(2,"B");
Node n3 = new Node(3,"C");
Node n4 = new Node(4,"D");
// LinkList linkList = new LinkList();
// linkList.add(n2);
// linkList.add(n1);
// linkList.add(n4);
// linkList.add(n3);
// linkList.list();
LinkList linkList2 = new LinkList();
linkList2.addOrder(n2);
linkList2.addOrder(n1);
linkList2.addOrder(n4);
linkList2.addOrder(n3);
linkList2.addOrder(n3);
linkList2.list();
Node n44 = new Node(4,"D~");
linkList2.update(n44);
linkList2.list();
System.out.println("删除");
linkList2.del(3);
linkList2.list();
}
}
class LinkList{
//头结点
private Node head = new Node(0,"");
private boolean addMethod = false;
//顺序插入
public void add(Node node){
this.addMethod = true;
Node temp = head;
//找尾结点
while (true){
if (temp.next==null){
break;
}
temp = temp.next;
}
temp.next = node;
}
//有序插入 根据no
public void addOrder(Node node){
if (addMethod){
System.out.println("有序插入不能与add()调用后使用!");
return;
}
Node temp = head;
boolean flag = false; //重复的no
while (true){
if (temp.next==null){
break;
}else if (temp.next.no == node.no){
flag = true;
System.out.println("存在重复的Node");
break;
}else if (temp.next.no > node.no){
break;
}
temp = temp.next;
}
if (!flag){
node.next = temp.next;
temp.next = node;
}
}
//修改 根据no 修改data
public void update(Node node){
if (head.next==null){
System.out.println("链表为空");
return;
}
Node temp = head.next;
boolean flag = false; //是否存在该节点
while (true){
if (temp == null){
break;
}
if (temp.no == node.no){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.data = node.data;
}else {
System.out.println("不存在该结点,不能修改");
}
}
//根据no删除结点
public void del(int no){
Node temp = head;
boolean flag = false; //是否存在该结点
while (true){
if (temp.next == null){
break;
}
if (temp.next.no == no){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.next = temp.next.next;
}else {
System.out.println("不存在该结点,不能删除");
}
}
//显示单链表
public void list(){
if (head.next==null){
System.out.println("链表为空");
return;
}
Node temp = head.next;
while (true){
if (temp!=null){
System.out.println(temp);
temp = temp.next;
}else {
break;
}
}
}
}
class Node{
public int no;
public String data;
public Node next;
public Node(int no, String data) {
this.no = no;
this.data = data;
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
", data='" + data + '\'' +
'}';
}
}
标签:als break 存在 boolean null 删除 return demo method
原文地址:https://www.cnblogs.com/fly-book/p/11630969.html