作为一名小白,在学习链表中遇到许许多多的困难,只要相信自己可以,多画图帮助自己思考理解,比别人多努力,多写几遍,总会熟练地掌握链表,没有解决不了的困难,只有不努力的人。
带头傀儡结点比较简单,下来先看一下创建代码和测试:
创建
class ListNode{
public int val;
public ListNode next;
public ListNode prev;
public ListNode (int val){
this.val = val;
}
}
public class DoubleList {
public ListNode puppetHead;//带傀儡节点的头节点
public ListNode last;
public DoubleList(){
this.puppetHead = new ListNode(-1);
}
//头插法
public void addFirst (int data){
ListNode node = new ListNode(data);
if (this.puppetHead.next == null) {
this.puppetHead.next = node;
node.prev = this.puppetHead;
this.last = node;
return;
}
node.next = this.puppetHead.next;
node.next.prev = node;
this.puppetHead.next = node;
node.prev = this.puppetHead;
}
//尾插法
public void addLast (int data){
ListNode node = new ListNode(data);
if (this.last == null && this.puppetHead.next == null) {
this.puppetHead.next = node;
node.prev = this.puppetHead;
this.last = node;
return;
}
this.last.next = node;
node.prev = this.last;
this.last = node;
}
//任意位置插入
public ListNode searchIndex (int index){
ListNode cur = this.puppetHead.next;
if (index < 0 && index > size()){
return null;
}
while (index < 0){
cur = cur.next;
index--;
}
return cur;
}
public void addIndex (int index, int data){
if (index == 0){
addFirst(data);
return;
}
if (index == size()) {
addLast(data);
return;
}
ListNode node = new ListNode(dat