写在前面,csdn的那篇同名博客就是我写的,我把它现在在这边重新发布,因为我实在不想用csdn了,那边的广告太多了,还有就是那个恶心人的“阅读更多”按钮,惹不起我躲得起。
在上次分享完单向链表的简单编写后,索性对于双向链表进行了一定的了解,在上次的基础上进行了一定程度的改进,做了一个非循环的双向链表。
双向链表的特点在于每个节点不仅知道自己的下属节点而且还知道自己的父节点。在双向链表的逆序方法中,我使用的队列来支持这个操作,利用了队列的先进先出的特点。
package demo_4; import java.util.Stack; public class MyDoubleList<Re_Helix> {
//节点内部类;
private class Node{
private Re_Helix data; //数据;
private Node next = null; //下个节点的引用;
private Node previous = null; //上个节点的引用; public Node() { //节点的无参构造;
super();
} public Node(Re_Helix data) { //节点的有参构造;
super();
this.data = data;
}
} private Node head; //头部节点;
private Node end; //尾部节点;
private Node point; //临时节点;
private Node point_pre; //临时节点2;
private int length; //长度属性; public MyDoubleList() { //链表的无参构造;
head = new Node();
end = head;
length = 0;
} public int length() { //返回链表的长度;
return length;
} public void showAll() { //在控制台查看当前链表中的所有数据
point = head;
int i = 0;
while(point!=null) {
System.out.println("第"+(i++)+"个:"+point.data);
point = point.next;
}
} public Re_Helix getById(int target) { //输入下标返回值;
return packPoint(target).data;
} public void input(Re_Helix data) {
point = new Node(data);
if(length==0) {
end.data = point.data;
}else {
point_pre = end;
end.next = point;
end = point;
point.previous = point_pre;
}
length++;
} public void inputById(int target,Re_Helix data) {
point = packPoint(target);
Node temp = new Node(data);
if(target>=length) {
end.next = temp;
temp.previous = end;
end = temp;
}else if(target<=0) {
temp.next = head;
head.previous = temp;
head = temp;
}else {
temp.next = point;
temp.previous = point.previous;
point.previous.next = temp;
point.previous = temp;
}
length++;
} public void deleteById(int target) { //输入下标删除值
if(target>0) {
packPoint(target-1).next = packPoint(target).next;
packPoint(target).next.previous = packPoint(target-1);
}else {
head.next.previous = null;
head = head.next;
}
length--;
} public void deleteAll() { //清空链表;
length = 0;
head.data = null;
head.next = null;
point = null;
end = head;
System.gc();
} public boolean editById(int target,Re_Helix data) { //修改传入下标位置的值;
if(target<0 || target>length) {
return false;
}else {
packPoint(target).data = data;
return true;
}
} public void reverse() { //将链表反转;
Stack<Node> s1 = new Stack<Node>(); //利用队列的先进先出的特性;
point = head;
while(point!=null) {
s1.push(point);
point = point.next;
}
head = s1.pop();
head.previous = null;
point = head;
while(!s1.isEmpty()) {
point.next = s1.pop();
point_pre = point;
point = point.next;
point.previous = point_pre;
}
end = point;
end.next = null; //要将逆序后的end位置节点的next置空,不然会造成最后两位的循环;
} private Node packPoint(int target) { //内部方法,将指针指向指定下标的节点;
if(target<=0) {
point = head;
}else if(target>=length) {
point = end;
}else {
int i = 0;
point = head;
while(i++!=target) {
point = point.next;
}
}
return point;
}
}
本文为我的原创文章,转载必须注明链接和我的ID:sunziren,否则就等着被举报吧,尤其是那什么狗屁“金铭鼎”教育。
多有不足,欢迎评论区批评指正。