更新時間:2022-05-17 10:01:55 來源:動力節點 瀏覽980次
鏈表是包含一系列連接節點的線性數據結構。在這里,每個節點存儲下一個節點的數據和地址。例如,
你必須從某個地方開始,所以我們給第一個節點的地址一個特殊的名字,叫做頭. 此外,可以識別鏈表中的最后一個節點,因為它的下一部分指向空值.
鏈表可以有多種類型:單鏈表、雙鏈表和循環鏈表。在本文中,我們將重點介紹單鏈表。要了解其他類型,請訪問鏈式存儲結構。
讓我們看看鏈表的每個節點是如何表示的。每個節點包括:
一個數據項
另一個節點的地址
我們將數據項和下一個節點引用包裝在一個結構中,如下所示:
struct node
{
int data;
struct node *next;
};
了解鏈表節點的結構是掌握它的關鍵。
每個結構節點都有一個數據項和一個指向另一個結構節點的指針。讓我們創建一個包含三個項目的簡單鏈接列表,以了解其工作原理。
/* Initialize nodes */
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
/* Assign data values */
one->data = 1;
two->data = 2;
three->data=3;
/* Connect nodes */
one->next = two;
two->next = three;
three->next = NULL;
/* Save address of first node in head */
head = one;
如果你不理解上面的任何一行,你只需要復習一下指針和結構。
只需幾個步驟,我們就創建了一個包含三個節點的簡單鏈表。
鏈表的力量來自于打破鏈并重新加入它的能力。例如,如果您想將元素 4 放在 1 和 2 之間,則步驟如下:
創建一個新的結構節點并為其分配內存。
將其數據值添加為 4
將其 next 指針指向包含 2 作為數據值的結構節點
將“1”的next指針更改為我們剛剛創建的節點。
在數組中做類似的事情需要移動所有后續元素的位置。
// Linked list implementation in Java
class LinkedList {
// Creating a node
Node head;
static class Node {
int value;
Node next;
Node(int d) {
value = d;
next = null;
}
}
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
// Assign value values
linkedList.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
// Connect nodess
linkedList.head.next = second;
second.next = third;
// printing node-value
while (linkedList.head != null) {
System.out.print(linkedList.head.value + " ");
linkedList.head = linkedList.head.next;
}
}
}
以上就是關于“數據結構鏈表的介紹”,大家如果想了解更多相關知識,不妨來關注一下動力節點的Java在線學習,里面的課程內容從入門到精通,細致全面,很適合沒有基礎的小伙伴學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習