package link;

public class Link {

/**
* 保存每一個節點,此處为了方便直接定義成內部類 
* @author binchen
*
*/
class Node{
private String data;
private Node next; //保存下一個節點

public Node(){}
public Node(String data){
this.data = data; //通過構造方法設置節點內容
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}

/**
* 輸出節點內容
*/
public void print(){
System.out.println(this.data + "\t");
if(this.next != null){
this.next.print();
}
}

/**
* 添加節點內容
* @param newNode
*/
public void add(Node newNode){ //將節點加入到合适的位置
if(this.next == null){
this.next = newNode;
}else{ //如果不为空,則需要向下繼續找next
this.next.add(newNode);
}
}

/**
* 查找節點
* @param data
* @return
*/
public boolean search(String data){ //內部搜索的方法
if(this.data.equals(data)){
return true;
}else{ //向下繼續判斷
if(this.next != null){ //如果不等於null,就繼續向下查找下去
return this.next.search(data);
}
return false;
}
}

/**
* 刪除節點
* @param data
*/
public void deleteNode(Node previous , String name){
if(name.equals(this.data)){
previous.next = this.next;
}else{
if(this.next != null){
this.next.deleteNode(this, name);
}
}
}
};



private Node root; //鏈表中必然存在一個根節點
public void setRoot(Node root){
this.root = root;
}
public Node getRoot(){
return this.root;
}

/**
* 添加節點內容
* @param data
*/
public void addNode(String data){ //增加節點
Node newNode = new Node(data); //定義新的節點
if(this.root == null){ //判斷根節點是否存在,如果不存在就將第一個節點設置成根節點
this.root = newNode; //將第一個節點設置成根節點
}else{ //不過如果存在,【不是根節點】,放到最後一個節點之後
this.root.add(newNode);
}
}

/**
* 輸出全部的節點內容
*/
public void printNode(){
if(this.root != null){ //如果根元素不为空
this.root.print(); //調用節點類中的輸出操作
}
}

/**
* 查找節點
* @param name
* @return
*/
public boolean contains(String name){
return this.root.search(name); //調用node類中的查找方法
}

/**
* 刪除節點
* @param name
*/
public void deleteNode(String data){
if(this.contains(data)){ //判斷節點是否存在
//一定要判斷此元素現在是不是與根元素相等
if(this.root.data.equals(data)){ //內容是根節點
this.root = this.root.next;  //修改根節點,將第一個節點設置成根節點
}else{
this.root.next.deleteNode(root,data);
}
}
}
}

arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()