DSA的C++实现
时间: 2023-07-11 12:03:40 浏览: 85
以下是一些常见数据结构和算法的C++实现:
1. 链表
```cpp
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* curr = head;
while (curr != NULL) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
head = reverseList(head);
while (head != NULL) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
return 0;
}
```
2. 栈
```cpp
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
cout << endl;
return 0;
}
```
3. 队列
```cpp
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<int> q;
q.push(1);
q.push(2);
q.push(3);
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
cout << endl;
return 0;
}
```
4. 二叉树
```cpp
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void preorderTraversal(TreeNode* root) {
if (root != NULL) {
cout << root->val << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}
void inorderTraversal(TreeNode* root) {
if (root != NULL) {
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}
}
void postorderTraversal(TreeNode* root) {
if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->val << " ";
}
}
int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
preorderTraversal(root);
cout << endl;
inorderTraversal(root);
cout << endl;
postorderTraversal(root);
cout << endl;
return 0;
}
```
5. 快速排序
```cpp
#include <iostream>
#include <vector>
using namespace std;
int partition(vector<int>& nums, int l, int r) {
int pivot = nums[l];
int i = l + 1, j = r;
while (true) {
while (i <= j && nums[i] < pivot) i++;
while (i <= j && nums[j] > pivot) j--;
if (i > j) break;
swap(nums[i], nums[j]);
i++;
j--;
}
swap(nums[l], nums[j]);
return j;
}
void quicksort(vector<int>& nums, int l, int r) {
if (l < r) {
int pivot_index = partition(nums, l, r);
quicksort(nums, l, pivot_index - 1);
quicksort(nums, pivot_index + 1, r);
}
}
int main() {
vector<int> nums = {3, 7, 2, 9, 4, 5, 1, 8, 6};
quicksort(nums, 0, nums.size() - 1);
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
```
以上是一些常见数据结构和算法的C++实现,希望对你有所帮助!
阅读全文