数据结构应用实现

ops/2024/10/19 7:58:10/

每种数据结构的实现通常可以通过多种语言来完成,以下是一些常用数据结构的基本实现示例,使用C++和Python分别演示:

1. 数组(Array)

C++ 实现
#include <iostream>
using namespace std;int main() {int arr[5] = {1, 2, 3, 4, 5};for(int i = 0; i < 5; i++) {cout << arr[i] << " ";}return 0;
}
Python 实现
arr = [1, 2, 3, 4, 5]
for elem in arr:print(elem, end=' ')

2. 链表(Linked List)

C++ 单链表实现
#include <iostream>
using namespace std;struct Node {int data;Node* next;
};void insert(Node** head, int data) {Node* newNode = new Node();newNode->data = data;newNode->next = *head;*head = newNode;
}void printList(Node* node) {while (node != nullptr) {cout << node->data << " ";node = node->next;}
}int main() {Node* head = nullptr;insert(&head, 1);insert(&head, 2);insert(&head, 3);printList(head);return 0;
}
Python 单链表实现
class Node:def __init__(self, data):self.data = dataself.next = Noneclass LinkedList:def __init__(self):self.head = Nonedef insert(self, data):new_node = Node(data)new_node.next = self.headself.head = new_nodedef print_list(self):temp = self.headwhile temp:print(temp.data, end=' ')temp = temp.nextll = LinkedList()
ll.insert(1)
ll.insert(2)
ll.insert(3)
ll.print_list()

3. 栈(Stack)

C++ 实现
#include <iostream>
#include <stack>
using namespace std;int main() {stack<int> s;s.push(10);s.push(20);s.push(30);while (!s.empty()) {cout << s.top() << " ";s.pop();}return 0;
}
Python 实现
stack = []
stack.append(10)
stack.append(20)
stack.append(30)while stack:print(stack.pop(), end=' ')

4. 队列(Queue)

C++ 实现
#include <iostream>
#include <queue>
using namespace std;int main() {queue<int> q;q.push(10);q.push(20);q.push(30);while (!q.empty()) {cout << q.front() << " ";q.pop();}return 0;
}
Python 实现
from collections import dequequeue = deque([10, 20, 30])while queue:print(queue.popleft(), end=' ')

5. 哈希表(Hash Table)

C++ 实现
#include <iostream>
#include <unordered_map>
using namespace std;int main() {unordered_map<string, int> hashTable;hashTable["apple"] = 1;hashTable["banana"] = 2;for (auto& pair : hashTable) {cout << pair.first << ": " << pair.second << endl;}return 0;
}
Python 实现
hash_table = {"apple": 1, "banana": 2}
for key, value in hash_table.items():print(f"{key}: {value}")

6. 二叉树(Binary Tree)

C++ 实现
#include <iostream>
using namespace std;struct Node {int data;Node* left;Node* right;Node(int val) : data(val), left(nullptr), right(nullptr) {}
};void inOrder(Node* node) {if (node == nullptr) return;inOrder(node->left);cout << node->data << " ";inOrder(node->right);
}int main() {Node* root = new Node(1);root->left = new Node(2);root->right = new Node(3);root->left->left = new Node(4);root->left->right = new Node(5);inOrder(root);return 0;
}
Python 实现
class Node:def __init__(self, data):self.data = dataself.left = Noneself.right = Nonedef in_order(node):if not node:returnin_order(node.left)print(node.data, end=' ')in_order(node.right)root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
in_order(root)

7. 图(Graph)

C++ 邻接表实现
#include <iostream>
#include <vector>
using namespace std;class Graph {int V;vector<int>* adj;
public:Graph(int V);void addEdge(int v, int w);void printGraph();
};Graph::Graph(int V) {this->V = V;adj = new vector<int>[V];
}void Graph::addEdge(int v, int w) {adj[v].push_back(w);
}void Graph::printGraph() {for (int v = 0; v < V; ++v) {cout << v << ": ";for (int x : adj[v])cout << x << " ";cout << endl;}
}int main() {Graph g(4);g.addEdge(0, 1);g.addEdge(0, 2);g.addEdge(1, 2);g.addEdge(2, 0);g.addEdge(2, 3);g.printGraph();return 0;
}
Python 邻接表实现
class Graph:def __init__(self, vertices):self.V = verticesself.graph = [[] for _ in range(vertices)]def add_edge(self, v, w):self.graph[v].append(w)def print_graph(self):for i in range(self.V):print(f"{i}: {self.graph[i]}")g = Graph(4)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.print_graph()

8. 堆(Heap)

C++ 实现(最大堆)
#include <iostream>
#include <queue>
using namespace std;int main() {priority_queue<int> maxHeap;maxHeap.push(10);maxHeap.push(5);maxHeap.push(20);while (!maxHeap.empty()) {cout << maxHeap.top() << " ";maxHeap.pop();}return 0;
}
Python 实现(最小堆)
import heapqmin_heap = []
heapq.heappush(min_heap, 10)
heapq.heappush(min_heap, 5)
heapq.heappush(min_heap, 20)while min_heap:print(heapq.heappop(min_heap), end=' ')

总结

这些是一些常见的数据结构的基本实现,使用不同的编程语言可以用不同的语法和方法来实现它们的操作。


http://www.ppmy.cn/ops/124966.html

相关文章

Go实现递归遍历文件夹

文件夹的递归遍历是操作系统编程中的常见需求&#xff0c;特别是在处理大量文件时&#xff0c;比如查找特定文件、统计文件数量、展示文件结构等。 需求分析 我们需要完成以下步骤&#xff1a; 读取当前文件夹下的所有文件和子文件夹。如果遇到子文件夹&#xff0c;进入该文…

初知C++:AVL树

文章目录 初知C&#xff1a;AVL树1.AVL树的概念2.AVL树的是实现2.1.AVL树的结构2.2.AVL树的插入2.3.旋转2.4.AVL树的查找2.5.AVL树平衡检测 初知C&#xff1a;AVL树 1.AVL树的概念 • AVL树是最先发明的自平衡⼆叉查找树&#xff0c;AVL是⼀颗空树&#xff0c;或者具备下列性…

Redis主从复制机制详解

目录 一、主从复制介绍二、搭建主从复制三、主从复制流程四、关于Replication ID五、主从复制核心知识六、主从复制应用场景七、主从复制的注意事项八、读写分离实战 一、主从复制介绍 1、什么是主从复制&#xff1f; 2、为什么要使用主从复制&#xff1f; redis-server单点…

Java - SpringBoot(基础)

SpringBoot基础 概述 SpringBoot是Spring提供的一个子项目&#xff0c;用于快速构建Spring应用程序。SpringBoot特性1.起步依赖 本质上就是一个Maven坐标&#xff0c;整合了完成一个功能需要的所有坐标。就是通过一个依赖&#xff0c;可以代替所有所需的依赖。2.自动配置 遵循…

CentOS 系统上将 Python 更新到 3.9 版本

1.首先&#xff0c;更新系统包并安装必要的开发工具 sudo yum update sudo yum groupinstall "Development Tools" -y sudo yum install openssl-devel bzip2-devel libffi-devel -y 2.下载 Python 3.9 源代码&#xff1a; cd /opt sudo wget https://…

三次握手与四次挥手

一、三次握手 AB之间 都会发送一个syn - ack。 A 先发 syn ,B收到 。 A: 什么都不知道 B:知道A可以发送。 B发送syn-ack,A收到 。 A: 知道B可以收也可以发 , B知道A可以发送。 A发送ack&#xff0c;B收到。 A &#xff1a; 知道B可以收也可以发 , B知道A…

2013年国赛高教杯数学建模C题古塔的变形解题全过程文档及程序

2013年国赛高教杯数学建模 C题 古塔的变形 由于长时间承受自重、气温、风力等各种作用&#xff0c;偶然还要受地震、飓风的影响&#xff0c;古塔会产生各种变形&#xff0c;诸如倾斜、弯曲、扭曲等。为保护古塔&#xff0c;文物部门需适时对古塔进行观测&#xff0c;了解各种变…

Root me CTF all the day靶场ssrf+redis漏洞

Rootme CTF all the day靶场ssrfredis漏洞 一、环境介绍1、漏洞地址2、漏洞介绍 二、 搭建环境三、测试过程3.1 读取系统文件3.2 探测开放的服务器端口(dict协议)3.3 redis未授权访问3.3.1 利用redis来写ssh密钥&#xff08;gopher协议写入&#xff09;3.3.2 利用redis写定时任…