java简单实现链表

来源:互联网 发布:linux sprintf函数 编辑:程序博客网 时间:2024/05/22 15:49
package link_data;public class Link {private int count = 0;//计数器private Node root;//头节点//////////////////////内部类 startprivate class Node{private String data;private Node next;public Node(String data)//初始化数据点{this.data = data;}public void addNode(Node newNode){//添加数据点if(this.next == null)this.next = newNode;elsethis.next.addNode(newNode);}public boolean containsNode(String data)//判断该数据是否存在{if(data.equals(this.data)){return true;}else{if(this.next != null)return this.next.containsNode(data);elsereturn false;}}public void removeNode(Node previous,String data){if(this.data.equals(data))previous.next = this.next;elsethis.next.removeNode(this, data);}public void toArrayNode(){Link.this.retData[Link.this.foot++] = this.data;if(this.next != null){this.next.toArrayNode();}}public String getNode(int index)//inside class find index for conce{if(Link.this.foot++==index){return this.data;}else{    return this.next.getNode(index);}}}///inside class finish//外部类调用内部类方法public boolean add(String data){//添加链表节点(数据)if(data == null)return false;Node newNode = new Node(data);if(this.root == null)this.root = newNode;elsethis.root.addNode(newNode);this.count++;return true;}public boolean addAll(String data[])//从数组添加节点{for(int x = 0 ;x < data.length ; x++){if(!this.add(data[x]))return false;}return true;}public int size(){//外部寻找断节点个数return this.count;}public boolean isEmpty()//外部类判断是否为空链表{return this.count == 0;}public boolean contains(String data)//外部类判断是否存在节点{if(this.root == null || data == null){return false;}return this.root.containsNode(data);}public void remove(String data)//删除数据点{if(!this.contains(data)){return ;}if(data.equals(this.root.data)){this.root = this.root.next;}else{this.root.next.removeNode(this.root,data);}this.count--;}public boolean changeFlag = true;public int foot = 0;private String[] retData;public String[] toArray(){if(this.count == 0){return null;}if(this.changeFlag == true){    this.foot = 0;    this.retData = new String[this.count];    this.root.toArrayNode();    this.changeFlag = false;}    return this.retData;}public String get(int index){if(index > this.count){return null;}this.foot = 0;return this.root.getNode(index);}public void clear(){this.root = null;this.count = 0;}}


0 0