您好,登錄后才能下訂單哦!
public void addFirst(int data) { //頭插
DLinkedNode newNode = new DLinkedNode(data);//加入的新節點
DLinkedNode next = head.next;
newNode.next = next;
next.prev = newNode;
head.next = newNode;
newNode.prev = head;
}
public void addLast(int data) {//尾插
DLinkedNode newNode = new DLinkedNode(data);//新插入的節點
DLinkedNode prev = head.prev;
newNode.next = head;
head.prev = newNode;
newNode.prev = prev;
prev.next = newNode;
}
public void addIndex(int index,int data) {//任意位置插入
int size = size();
if(index < 0 || index > size){
return;
}
if(index == 0){
addFirst(data);
return;
}
if(index == size) {
addLast(data);
return;
}
DLinkedNode next = getPos(index);
DLinkedNode prev = next.prev;
DLinkedNode newNode = new DLinkedNode(data);
prev.next = newNode;
newNode.prev = prev;
next.prev = newNode;
newNode.next = next;
}
這里用到的計算鏈表長度的方法:
public int size(){
int size = 0;
for(DLinkedNode cur = head.next; cur != head; cur = cur.next) {
size++;
}
return size;
}
和查找鏈表中某一位置的方法:
public DLinkedNode getPos(int index) {
DLinkedNode cur = head.next;
for(int i = 0; i < index; i++){
cur = cur.next;
}
return cur;
}
public boolean contains(int key) {//查找是否包含關鍵字key的節點
for(DLinkedNode cur = head.next; cur != head; cur = cur.next) {
if(cur.val == key){
return true;
}
}
return false;
}
public void remove(int key){
DLinkedNode toRemove = find(key);
if(toRemove == null) {
return;
}
DLinkedNode prev = toRemove.prev;
DLinkedNode next = toRemove.next;
prev.next = next;
next.prev = prev;
}
這里用到查找關鍵字key在鏈表中的位置的方法:
public DLinkedNode find(int key) {
for(DLinkedNode cur = head.next; cur != head; cur = cur.next) {
if(cur.val == key){
return cur;
}
}
return null;
}
public void removeAll(int key){
while (true){
DLinkedNode toRmove = find(key);
if(toRmove == null){
return;
}
DLinkedNode prev = toRmove.prev;
DLinkedNode next = toRmove.next;
prev.next = next;
next.prev = prev;
}
}
public void display(){
System.out.print("正向:[");
for(DLinkedNode cur = head.next; cur != head; cur = cur.next){
System.out.print(cur.val);
if(cur.next != head){
System.out.print(",");
}
}
System.out.println("]");
System.out.println("反向:[");
for(DLinkedNode cur = head.prev; cur != head; cur = cur.prev){
System.out.print(cur.val);
if(cur.prev != head){
System.out.print(",");
}
}
System.out.println("]");
}
public void clear(){
head.next = head;
head.prev = head;
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。