前期文章点击这里:
链表数据结构包括一系列连接的节点。在这里,每个节点都存储下一个节点的数据和地址。例如:
Linkedin数据结构
您必须从某个地方开始,所以我们给第一个节点的地址一个特殊的名字,叫做头。
另外,可以确定链表中的最后一个节点,因为其下一部分指向空值。您可能玩过寻宝游戏,其中每个线索都包含有关下一个线索的信息。这就是链接列表的操作方式。
LinkedList的表示
让我们看看如何表示LinkedList的每个节点。每个节点包括:
数据项
另一个节点的地址
我们将数据项和下一个节点引用都包装在一个结构中,如下所示:
struct node{int data;struct node *next;};
了解链接列表节点的结构是掌握链接列表节点的关键。
每个结构节点都有一个数据项和一个指向另一个结构节点的指针。让我们创建一个包含三个项目的简单链接列表,以了解其工作原理。
struct node *head;struct node *one = NULL;struct node *two = NULL;struct node *three = NULL;one = malloc(sizeof(struct node));two = malloc(sizeof(struct node));three = malloc(sizeof(struct node));one->data = 1;two->data = 2;three->data=3;one->next = two;two->next = three;three->next = NULL;head = one;
如果您不懂上述任何几行,则只需要复习一下指针和结构。
仅需几个步骤,我们就创建了一个包含三个节点的简单链表。
LinkedList表示形式
LinkedList的功能来自断开链并重新加入链的能力。例如,如果您想将元素4放在1和2之间,则步骤为:
创建一个新的结构节点并为其分配内存。
将其数据值添加为4
将其下一个指针指向包含2作为数据值的struct节点
将下一个指针“ 1”更改为我们刚刚创建的节点。
在数组中执行类似操作将需要移动所有后续元素的位置。
在python和Java中,可以使用下面的代码所示的类来实现链表。
链表实用程序
列表是最流行和最有效的数据结构之一,可以在每种编程语言(如C,C ++,Python,Java和C#)中实现。
除此之外,链接列表是了解指针如何工作的好方法。通过练习如何操作链表,您可以准备学习更高级的数据结构,例如图形和树。
Python,C和C ++示例中的链接列表实现
class Node:def __init__(self, item):self.item = itemself.next = Noneclass LinkedList:def __init__(self):self.head = Noneif __name__ == '__main__':linked_list = LinkedList()linked_list.head = Node(1)second = Node(2)third = Node(3)linked_list.head.next = secondsecond.next = thirdwhile linked_list.head != None:print(linked_list.head.item, end=" ")linked_list.head = linked_list.head.next
#include #include struct node {int value;struct node *next;};void printLinkedlist(struct node *p){while (p != NULL) {printf("%d ", p->value);p = p->next;}}int main(){struct node *head;struct node *one = NULL;struct node *two = NULL;struct node *three = NULL;one = malloc(sizeof(struct node));two = malloc(sizeof(struct node));three = malloc(sizeof(struct node));one->value = 1;two->value = 2;three->value = 3;one->next = two;two->next = three;three->next = NULL;head = one;printLinkedlist(head);}
#include using namespace std;class Node{public:int value;Node* next;};int main() {Node* head;Node* one = NULL;Node* two = NULL;Node* three = NULL;one = new Node();two = new Node();three = new Node();one->value = 1;two->value = 2;three->value = 3;one->next = two;two->next = three;three->next = NULL;head = one;while (head != NULL) {printf("%d ", head->value);head = head->next;}}
链表应用
动态内存分配
在堆栈和队列中实现
在撤销软件的功能
哈希表,图形