????????在Java中,鏈表可以通過創(chuàng)建節(jié)點(diǎn)和鏈接節(jié)點(diǎn)來實(shí)現(xiàn)。以下是一個(gè)簡單的鏈表實(shí)現(xiàn)示例:
public class LinkedList {
Node head; // 頭結(jié)點(diǎn)
// 節(jié)點(diǎn)類
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
// 在鏈表頭部插入節(jié)點(diǎn)
public void push(int new_data) {
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
// 在鏈表中間插入節(jié)點(diǎn)
public void insertAfter(Node prev_node, int new_data) {
if (prev_node == null) {
System.out.println("The given previous node cannot be null");
return;
}
Node new_node = new Node(new_data);
new_node.next = prev_node.next;
prev_node.next = new_node;
}
// 在鏈表尾部插入節(jié)點(diǎn)
public void append(int new_data) {
Node new_node = new Node(new_data);
if (head == null) {
head = new Node(new_data);
return;
}
new_node.next = null;
Node last = head;
while (last.next != null)
last = last.next;
last.next = new_node;
return;
}
// 刪除鏈表中的給定節(jié)點(diǎn)
public void deleteNode(int key) {
Node temp = head, prev = null;
if (temp != null && temp.data == key) {
head = temp.next;
return;
}
while (temp != null && temp.data != key) {
prev = temp;
temp = temp.next;
}
if (temp == null)
return;
prev.next = temp.next;
}
// 打印鏈表
public void printList() {
Node tnode = head;
while (tnode != null) {
System.out.print(tnode.data + " ");
tnode = tnode.next;
}
}
// 測試
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.append(6);
list.push(7);
list.push(1);
list.append(4);
list.insertAfter(list.head.next, 8);
System.out.println("Created Linked list is: ");
list.printList();
list.deleteNode(1);
System.out.println("\nLinked List after Deletion of 1:");
list.printList();
}
}
輸出:文章來源:http://www.zghlxwxcb.cn/news/detail-621525.html
Created Linked list is:
1 7 8 6 4
Linked List after Deletion of 1:
7 8 6 4
????????在這個(gè)示例中,我們創(chuàng)建了一個(gè)?LinkedList?類,它包含一個(gè)?Node?類和一些方法來操作鏈表。我們可以使用?push()?方法在鏈表的頭部插入節(jié)點(diǎn),使用?insertAfter()?方法在鏈表中間插入節(jié)點(diǎn),使用?append()?方法在鏈表尾部插入節(jié)點(diǎn),使用?deleteNode()?方法刪除鏈表中的給定節(jié)點(diǎn),并使用?printList()?方法打印鏈表。文章來源地址http://www.zghlxwxcb.cn/news/detail-621525.html
到了這里,關(guān)于Java中鏈表的實(shí)現(xiàn)(超詳細(xì))的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!