链表:适合删除,和插入,不宜查询,链表长度不宜过长,遍历的效率低
输入:适合查找,不适合插入,删除;
链表的增删改查简单实现:
public class Demo { public static void main(String[] args){ ManageNode manage = new ManageNode(); manage.addnode(5); manage.addnode(3); manage.addnode(2); manage.addnode(4); manage.addnode(5); manage.printAllDode(); manage.insertnode(3,8);//在index位置插入数据8; manage.printAllDode(); manage.updatenode(3,1);//将index为3的数据移动到index为1的前面 manage.printAllDode(); manage.delnode(0); manage.printAllDode(); } } class ManageNode{ private Node root;//根节点 private static int count=1; private static Node temp_node; public void addnode(int data){ if(root==null){ root = new Node(data); }else{ root.addnode(data); } } public void delnode(int index){ if(index<=0){ return; } if(index==0){ root = root.nextDode; return; } count=1; root.delnode(index); } //在指定的index位置插入数据 public void insertnode(int index,int data){ if(index==0){ Node node = new Node(data); node.nextDode = root; root = node; return; }else{ root.insertnode(index,data); } } //将链表中的index位置的数据修改到new_index位置 public void updatenode(int old_index,int new_index){ if(old_index==0){ if(root.nextDode!=null){ temp_node = root; root = root.nextDode; } count=1; root.updateinsert(new_index); }else{ count=1; root.delnode(old_index); if(new_index==0){ temp_node.nextDode = root; root = temp_node; return; }else{ count=1; root.updateinsert(new_index); } } } //打印所有的链表的数据 public void printAllDode(){ if(root.nextDode!=null){ System.out.print(root.getData()+"-->"); root.printNode(); }else{ System.out.println(root.getData()); } } //成员内部类 private class Node{ private int data; private Node temp; private Node nextDode; public Node(int data){ this.data = data; } //添加数据,最后面添加 public void addnode(int data){ if(this.nextDode==null){ this.nextDode = new Node(data); }else{ this.nextDode.addnode(data); } } //删除数据 public void delnode(int old_index){ if(count==old_index){ temp_node = this.nextDode; this.nextDode = this.nextDode.nextDode; return; } count++; if(this.nextDode!=null){ this.nextDode.delnode(old_index); } } //在指定的位置插入数据,数据是自己传递进来的 public void insertnode(int index,int data){ if(index==count){ temp = this.nextDode; Node node = new Node(data); this.nextDode = node; node.nextDode = temp; return; }else{ count++; if(this.nextDode!=null){ this.nextDode.insertnode(index, data); } } } //在指定的位置插入数据,数据存放在了temp_node public void updateinsert(int new_index){ if(count==new_index){ temp_node.nextDode = this.nextDode; this.nextDode = temp_node; return; } count++; this.nextDode.updateinsert(new_index); } //获取数据 public int getData(){ return this.data; } //打印下个一个节点的数据 public void printNode(){ // System.out.print(this.nextDode+",this.nextDode"); if(this.nextDode.nextDode!=null){ System.out.print(this.nextDode.getData()+"-->"); this.nextDode.printNode(); }else{ System.out.println(this.nextDode.getData()); } } } }
原文:https://www.cnblogs.com/yanxiaoge/p/10679189.html