更新時間:2022-05-17 10:01:55 來源:動力節(jié)點 瀏覽990次
鏈表是包含一系列連接節(jié)點的線性數(shù)據(jù)結(jié)構(gòu)。在這里,每個節(jié)點存儲下一個節(jié)點的數(shù)據(jù)和地址。例如,
你必須從某個地方開始,所以我們給第一個節(jié)點的地址一個特殊的名字,叫做頭. 此外,可以識別鏈表中的最后一個節(jié)點,因為它的下一部分指向空值.
鏈表可以有多種類型:單鏈表、雙鏈表和循環(huán)鏈表。在本文中,我們將重點介紹單鏈表。要了解其他類型,請訪問鏈?zhǔn)酱鎯Y(jié)構(gòu)。
讓我們看看鏈表的每個節(jié)點是如何表示的。每個節(jié)點包括:
一個數(shù)據(jù)項
另一個節(jié)點的地址
我們將數(shù)據(jù)項和下一個節(jié)點引用包裝在一個結(jié)構(gòu)中,如下所示:
struct node
{
int data;
struct node *next;
};
了解鏈表節(jié)點的結(jié)構(gòu)是掌握它的關(guān)鍵。
每個結(jié)構(gòu)節(jié)點都有一個數(shù)據(jù)項和一個指向另一個結(jié)構(gòu)節(jié)點的指針。讓我們創(chuàng)建一個包含三個項目的簡單鏈接列表,以了解其工作原理。
/* 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;
如果你不理解上面的任何一行,你只需要復(fù)習(xí)一下指針和結(jié)構(gòu)。
只需幾個步驟,我們就創(chuàng)建了一個包含三個節(jié)點的簡單鏈表。
鏈表的力量來自于打破鏈并重新加入它的能力。例如,如果您想將元素 4 放在 1 和 2 之間,則步驟如下:
創(chuàng)建一個新的結(jié)構(gòu)節(jié)點并為其分配內(nèi)存。
將其數(shù)據(jù)值添加為 4
將其 next 指針指向包含 2 作為數(shù)據(jù)值的結(jié)構(gòu)節(jié)點
將“1”的next指針更改為我們剛剛創(chuàng)建的節(jié)點。
在數(shù)組中做類似的事情需要移動所有后續(xù)元素的位置。
// 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;
}
}
}
以上就是關(guān)于“數(shù)據(jù)結(jié)構(gòu)鏈表的介紹”,大家如果想了解更多相關(guān)知識,不妨來關(guān)注一下動力節(jié)點的Java在線學(xué)習(xí),里面的課程內(nèi)容從入門到精通,細致全面,很適合沒有基礎(chǔ)的小伙伴學(xué)習(xí),希望對大家能夠有所幫助。
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743