自定义链表

2019-07-12  本文已影响0人  一起DP吧

自定义链表

1 实现Node节点类

 Node 节点包含一个用来装载数据的容器和一个指向下一个Node节点的指针
 
 package node;

 import lombok.AllArgsConstructor;
 import lombok.Data;
 import lombok.NoArgsConstructor;

 /**
  * @Description 自定义节点class
  * @Authror taren
  * @DATE 2019/7/12 10:01
  */
 @Data
 @NoArgsConstructor
 @AllArgsConstructor
 public class CustomNode<T> {

 private T data;

 private CustomNode<T> next;

 public CustomNode(T data) {
    this.data = data;
 }

 //自定义增加节点的方法
 public void addNode(CustomNode t) {
     if (this.next == null) {
        this.next = t;
     } else {
        this.next.addNode(t);
     }
 }

 //打印节点的方法
 public void print() {
     if (null != this.data) {
         System.out.println(this.data);
     }

     if (null != this.next) {
        this.next.print();
     }
 }

 //删除Node的方法
 public void removeNode(String data) {
     if (this.next == null) {
         return;
     }
     if (this.next.getData().equals(data)) {
         this.next = this.next.getNext();
     } else {
         this.next.removeNode(data);
     }
 }
}

2 实现Link类

Link类包含一个root节点
package node;

import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Description 自定义链表class
 * @Authror taren
 * @DATE 2019/7/12 10:09
 */
@Data
@NoArgsConstructor
public class CustomLink {

private CustomNode root;

// 新增节点方法
public void add(String data) {
    if (data != null && data.trim().length() > 0) {
        CustomNode node = new CustomNode(data);
        if (this.root == null) {
            this.root = node;
        } else {
            this.root.addNode(node);
        }
    }
}
// 打印链表
public void print() {
    if (this.root != null) {
        this.root.print();
    }
}
// 移除节点
public void remove(String data) {
    if (this.root.getData().equals(data)) {
        this.root = this.root.getNext();
    } else {
        this.root.removeNode(data);
    }
}

}

3 编写测试类进行对链表进行测试

package node;

import org.junit.Test;

/**
 * @Description
 * @Authror taren
 * @DATE 2019/7/12 10:13
 */
public class LinkTest {

@Test
public void test01(){
    //增加节点
    CustomLink link = new CustomLink();
    link.add("节点A");
    link.add("节点B");
    link.add("节点C");
    link.add("节点D");
    link.print();
}

@Test
public void test02(){
    //增加节点
    CustomLink link = new CustomLink();
    link.add("节点A");
    link.add("节点B");
    link.add("节点C");
    link.add("节点D");
    //移除节点D
    link.remove("节点B");
    link.print();
}

@Test
public void test03(){
    //增加节点
    CustomLink link = new CustomLink();
    link.add("节点A");
    link.add("节点B");
    link.add("节点C");
    link.add("节点D");
    //打印节点信息
    link.getRoot().getNext().print();
}

}

上一篇 下一篇

猜你喜欢

热点阅读