色婷婷狠狠18禁久久YY,CHINESE性内射高清国产,国产女人18毛片水真多1,国产AV在线观看

java鏈表的種類和實現

韓華玲1年前6瀏覽0評論

在Java中,鏈表是一種非常常見的數據結構,它可以用于存儲一系列的元素,并且支持動態添加和刪除元素。在Java中,鏈表可以分為單向鏈表、雙向鏈表以及循環鏈表三種類型。下面我們來分別介紹一下它們的實現方式。

// 單向鏈表的實現
class Node {
int data;
Node next;
}
class LinkedList {
Node head;
public void add(int data) {
Node newNode = new Node();
newNode.data = data;
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
}
public void remove(int data) {
if (head == null) {
return;
}
if (head.data == data) {
head = head.next;
} else {
Node temp = head;
while (temp.next != null && temp.next.data != data) {
temp = temp.next;
}
if (temp.next != null) {
temp.next = temp.next.next;
}
}
}
}
// 雙向鏈表的實現
class Node {
int data;
Node prev;
Node next;
}
class LinkedList {
Node head;
public void add(int data) {
Node newNode = new Node();
newNode.data = data;
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
newNode.prev = temp;
}
}
public void remove(int data) {
if (head == null) {
return;
}
if (head.data == data) {
head = head.next;
if (head != null) {
head.prev = null;
}
} else {
Node temp = head;
while (temp != null && temp.data != data) {
temp = temp.next;
}
if (temp != null) {
temp.prev.next = temp.next;
if (temp.next != null) {
temp.next.prev = temp.prev;
}
}
}
}
}
// 循環鏈表的實現
class Node {
int data;
Node next;
}
class LinkedList {
Node head;
public void add(int data) {
Node newNode = new Node();
newNode.data = data;
if (head == null) {
head = newNode;
head.next = head;
} else {
Node temp = head;
while (temp.next != head) {
temp = temp.next;
}
temp.next = newNode;
newNode.next = head;
}
}
public void remove(int data) {
if (head == null) {
return;
}
if (head.data == data) {
Node temp = head;
while (temp.next != head) {
temp = temp.next;
}
temp.next = head.next;
head = head.next;
} else {
Node temp = head;
while (temp.next != head && temp.next.data != data) {
temp = temp.next;
}
if (temp.next != head) {
temp.next = temp.next.next;
}
}
}
}