单向链表;这个词汇对于我们都不是很陌生,特别是学习过数据结构的话,是更加不可少的一门知识。
由于是直接基于代码的,并没有相应的图片什么之类的,也是个人做一个记载。
实现链表代码的属性
public class Node {
// 数据
private int value;
// 下一个节点
private Node next;}
构造函数
public Node(int value) {
this.value = value;
}
public Node(int value,Node next) {
this.value = value;
this.next = next;
}// 相应的setter 和 getter方法
public int getValue() {
return value;
}public void setValue(int value) {
this.value = value;
}public Node getNext() {
return next;
}public void setNext(Node next) {
this.next = next;
}// 用于判断是否还有下一个节点
public boolean hasNext() {
return this.next != null;
}
尾插法
/**
* 尾插法;插入一个节点到尾部
* @param node
*/
public void addToTail(Node node) {
// 当前的节点
Node temp = this;
// 判断node是是否有下一个
while(temp.hasNext()) {
temp = temp.next;
}
// node 就是最后的下一个节点位置指向
temp.next = node;
}
头插法:
/**
* 头插法
* @param head
* @param node
*/
public void addToHead(Node head,Node node) {
// 将头部以后的节点都放在node以后的节点上
node.next = head.next;
// 然后头的节点就指向node位置
head.next = node;
}
往当前节点后插入数据
/**
* 往当前节点后面追截
* @param node
* @return
*/
public Node addToNext(Node node) {// 当前节点的下一个节点指向 给 node 的下一个节点
node.next = this.next;// 当前的节点指向指向 ndoe
this.next = node;// 返回node
return node;
}
链表的反转 : 在这个是基于while循环中进行替换和新的指向
public static Node newReverse(Node head) {
// 前驱节点
Node pre = head;
// 当前节点
Node cru = null;
if(head.hasNext()) {
cru = head.next;
} else {
return head;
}
pre.setNext(null);
while(cru.hasNext()) {
// 获取标记出来的下一个节点
Node after = cru.getNext();
// 将当前节点指向前驱节点
cru.setNext(pre);
// 现有当前节点该为前驱
pre = cru;
// 前驱节点指向下一个节点
cru = after;
}
cru.setNext(pre);
return cru;
}
其他的部分;后续继续更新.