在JAVA中的线性表的底层结构是数组,而链表在JAVA中的底层结构不是单向链表,而是双向链表。
双向链表的实现代码:
双向链表的主要函数:
头插法,尾插法,找到指定节点,指定位置插入,查找是不是含有值为key的节点,得到链表长度,删除第一个值为key的节点,删除所有值为key的节点,清除链表中的所有节点。
头插法:
public void addToHead(int n) {
Node cur = new Node(n);
if(head == null) {
this.head = cur;
this.last = cur;
} else {
cur.next = this.head;
this.head.prev = cur;
head = cur;
}
}
尾插法:
public void addToLast(int n) {
Node cur = new Node(n);
if(last == null) {
this.head = cur;
this.last = cur;
} else {
this.last.next = cur;
cur.prev = last;
last = cur;
}
}
得到链表长度:
public Node findIndex(int index) {
if (index < 0) {
return null;
}
if(index >sizeOflink()) {
return null;
}
Node cur = this.head;
while(index != 0) {
cur = cur.next;
index--;
}
return cur;
}
指定位置插入:
public void addToIndex(int n,int index) {
Node cur = findIndex(index);
Node node = new Node(n);
if(cur == null) {
System.out.println("位置不合法");
return;
}
if(cur == this.head) {
node.next = this.head;
this.head.prev = node;
this.head = node;
} else if (cur == this.last) {
node.prev = last;
last.next = node;
this.last = node;
} else {
node.next = cur;
node.prev = cur.prev;
cur.prev.next = node;
cur.prev = node;
}
}
查找是否含有值为key的节点:
public boolean contains(int key) {
Node cur = this.head;
while(cur != null) {
if(cur.val == key) {
return true;
}
cur = cur.next;
}
return false;
}
得到链表长度:
public int sizeOflink() {
int count = 0;
Node cur = this.head;
while(cur != null) {
cur = cur.next;
count++;
}
return count;
}
删除第一个值为key的节点:
public void remove(int key) {
Node cur = this.head;
while(cur != null) {
if(cur.val == key) {
if(this.head == this.last) {
this.head = null;
this.last = null;
return;
}
if(cur == this.head) {
this.head = this.head.next;
this.head.prev = null;
} else if(cur == this.last) {
this.last = this.last.prev;
this.last.next = null;
} else {
cur.prev.next = cur.next;
cur.next.prev = cur.prev;
}
return;
}
cur = cur.next;
}
}
删除所有值为key的节点:
public void remove(int key) {
Node cur = this.head;
while(cur != null) {
if(cur.val == key) {
if(this.head == this.last) {
this.head = null;
this.last = null;
return;
}
if(cur == this.head) {
this.head = this.head.next;
this.head.prev = null;
} else if(cur == this.last) {
this.last = this.last.prev;
this.last.next = null;
} else {
cur.prev.next = cur.next;
cur.next.prev = cur.prev;
}
}
cur = cur.next;
}
}
清除链表中所有节点:
public void clear() {
Node cur = this.head;
while(cur != null) {
Node curNext = cur.next;
cur.prev = null;
cur.next = null;
cur = cur.next;
}
this.head = null;
this.last = null;
}