用python 中的链表 实现 截取其中一部分_经典数据结构与算法(五):Python/C/C ++实现链表...

前期文章点击这里:

链表数据结构包括一系列连接的节点。在这里,每个节点都存储下一个节点的数据和地址。例如:

3cc4c239432a16b6ccc62b06a7cd7525.png

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;

如果您不懂上述任何几行,则只需要复习一下指针和结构。

仅需几个步骤,我们就创建了一个包含三个节点的简单链表。

1b6c8e083c273551bf4e8f6795a83cb6.png

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;}}

链表应用

动态内存分配

在堆栈和队列中实现

在撤销软件的功能

哈希表,图形

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值