上一章:数据结构复习(4)—队列
package cjy.datastructure;
/**
* 节点 Title: Node.java 单链表
*
* @author CJY》10258
* @date 2019年7月12日
*/
public class Node {
/**
* 节点对应的值(数值域)
*/
int data;
/**
* 下一个节点的位置(节点域)
*/
Node next = null;
/**
* 构建新节点
*
* @param data
* 节点的值
*/
public Node(int data) {
this.data = data;
}
/**
* 链接下一个节点
*
* @param node
* @return
*/
public Node append(Node newNode) {
// 当前节点位置
Node curNode = this;
// 遍历整个链表
while (true) {
Node nextNode = curNode.next;
// 如果发现某个节点的next为空,则说明可以在该节点上链接新节点,跳出循环
if (nextNode == null) {
break;
}
// 将上面找到的节点作为当前节点(其实就是链表最后一个节点的位置)
curNode = nextNode;
}
// 将新节点赋值给当前节点(在链表结尾加入新节点)
curNode.next = newNode;
return this;
}
/**
* 转到下一个节点位置
*
* @return
*/
public Node next() {
return this.next;
}
/**
* 获取当前节点的值
*
* @return
*/
public int getData() {
return this.data;
}
/**
* 判断当前节点是否是最后一个节点
*
* @return
*/
public boolean isLastNode() {
return this.next == null;
}
/**
* 在当前节点后面插入新节点
*
* @param newNode
*/
public void insertNode(Node newNode) {
// 为空则直接插入,表尾
if (this.next == null) {
this.next = newNode;
} else {
Node node = next;
this.next = newNode;
newNode.next = node;
}
}
/**
* 删除当前节点的下一个节点
*/
public void removeNode() {
if (this.next == null) {
throw new RuntimeException("无下一个节点");
}
Node node = next.next;
this.next = node;
}
/**
* 获取节点长度
*
* @return
*/
public int length() {
Node curNode = this;
int count = 0;
while (true) {
count++;
curNode = curNode.next;
if (curNode == null) {
break;
}
}
return count;
}
/**
* 打印所有节点
*/
public void showNode() {
Node curNode = this;
while (true) {
System.out.print(curNode.data + " ");
curNode = curNode.next;
if (curNode == null) {
break;
}
}
System.out.println();
}
}