数据结构--实验

news2024/7/4 5:34:44

话不多说,直接启动!👌🤣

目录

一、线性表😎

1、建立链表 

 2、插入元素

3、删除特定位置的元素

 4、输出特定元素值的位置

5、输出特定位置的元素值

 6、输出整个链表

 实现

二、栈和队列😘

顺序栈

1、建立顺序栈

2、入栈

3、出栈

4、取栈顶

5、遍历栈

6、判栈空

实现: 

链栈

1、建立链栈

2、入栈

3、出栈

4、取栈顶

5、遍历栈

6、判栈空

实现: 

队列

顺序队列

1、建立顺序队列

2、入队

3、出队

4、求队列长度

5、遍历队列

实现:

链式队列

1、建立链式队列

2、入队

3、出队

4、求队列长度

5、遍历队列

实现:

 三、树和二叉树

实现:

 四、图

实现:

五、查找和排序

 折半查找实现:

快速排序实现: 


 

一、线性表😎

1、建立链表 

#include<iostream>
#include<vector>
using namespace std;
//定义单链表结点结构体 
struct ListNode{
	int val;
	ListNode* next;
};
//创建链表
ListNode* CreateList(){
	ListNode* head = new ListNode();//创建头结点
	head->next = nullptr;//初始化头结点的next指针为空
	
	return head; 
} 
int main(){
	ListNode* head = CreateList();
}

 2、插入元素

//在链表中插入元素
void Insert(ListNode* head, int i, int val) { // 需要链表,第i个位置,插入val值
    ListNode* current = head; // 初始化当前结点为头结点
    while (i-- > 0) { // 循环i次找插入位置
        current = current->next;
    }
    ListNode* newNode = new ListNode();
    newNode->val = val;
    newNode->next = current->next;
    current->next = newNode;
}

3、删除特定位置的元素

//删除特定位置的元素
void Delete(ListNode* head,int index){//需要链表,第i个位置
	if(index<0)return;
	ListNode* current = head;
	for(int i=0;i<index&&current!=nullptr;i++){
		current=current->next;
	}
	if(current==nullptr)return;
	ListNode* toDelete = current->next;
    current->next = current->next->next;
    delete toDelete;
}

 4、输出特定元素值的位置

//输出特定元素值的位置
void PrintValue(ListNode* head, int index) {
    ListNode* current = head;
    int position = 0;
    while (current != nullptr) {
        if (current->val == index) {
            cout << "元素值:" << current->val << " 的位置是:" << position << endl;
            break;
        }
        current = current->next;
        position++;
    }
    if (current == nullptr) {
        cout << "索引超出链表范围" << endl;
    }
}

5、输出特定位置的元素值

//输出特定位置的元素值
void PrintNodeAtPosition(ListNode* head, int index) {
    ListNode* current = head;
    for (int i = 0; i < index && current != nullptr; i++) {
        current = current->next;
    }
    if (current != nullptr) {
        cout << "元素位置:" << index << ", 值:" << current->val << endl;
    } else {
        cout << "索引超出链表范围" << endl;
    }
}

 6、输出整个链表

//输出整个链表
void PrintList(ListNode* head) {
    ListNode* current = head;
    while (current != nullptr) {
        cout << current->val << " --> ";
        current = current->next;
    }
    cout << "nullptr" << endl;
}

 实现

#include<iostream>
#include<vector>
using namespace std;
//定义单链表结点结构体 
struct ListNode{
	int val;
	ListNode* next;
};
//创建链表
ListNode* CreateList(){
	ListNode* head = new ListNode();//创建头结点
	head->next = nullptr;//初始化头结点的next指针为空
	
	return head; 
} 
//在链表中插入元素
void Insert(ListNode* head, int i, int val) { // 需要链表,第i个位置,插入val值
    ListNode* current = head; // 初始化当前结点为头结点
    while (i-- > 0) { // 循环i次找插入位置
        current = current->next;
    }
    ListNode* newNode = new ListNode();
    newNode->val = val;
    newNode->next = current->next;
    current->next = newNode;
}
//删除特定位置的元素
void Delete(ListNode* head,int index){//需要链表,第i个位置
	if(index<0)return;
	ListNode* current = head;
	for(int i=0;i<index&&current!=nullptr;i++){
		current=current->next;
	}
	if(current==nullptr)return;
	ListNode* toDelete = current->next;
    current->next = current->next->next;
    delete toDelete;
}
//从输入读取链表元素并插入
void ReadInputToList(ListNode* head) {
    cout << "请输入你需要建立的初始链表(只允许实数):" << endl;
    vector<double> LinkList;
    double input;
    while (cin >> input) {
        LinkList.push_back(input);
		if(cin.peek() == '\n'){
    		cin.ignore();
    		break;
		}
    }
    int index = 0;
    for (double value : LinkList) {
        Insert(head, index++, static_cast<int>(value)); // 将读取的实数转换为整数后插入链表
    }
} 
//输出特定元素值的位置
void PrintValue(ListNode* head, int index) {
    ListNode* current = head;
    int position = 0;
    while (current != nullptr) {
        if (current->val == index) {
            cout << "元素值:" << current->val << " 的位置是:" << position << endl;
            break;
        }
        current = current->next;
        position++;
    }
    if (current == nullptr) {
        cout << "索引超出链表范围" << endl;
    }
}

//输出特定位置的元素值
void PrintNodeAtPosition(ListNode* head, int index) {
    ListNode* current = head;
    for (int i = 0; i < index && current != nullptr; i++) {
        current = current->next;
    }
    if (current != nullptr) {
        cout << "元素位置:" << index << ", 值:" << current->val << endl;
    } else {
        cout << "索引超出链表范围" << endl;
    }
}
//输出整个链表
void PrintList(ListNode* head) {
    ListNode* current = head;
    while (current != nullptr) {
        cout << current->val << " --> ";
        current = current->next;
    }
    cout << "nullptr" << endl;
}
int main(){
	ListNode* head = CreateList();
	ReadInputToList(head);
	cout<<"1.输出链表中的所有结点"<<endl;
	PrintList(head);
	cout<<"2.输出元素25的位置"<<endl;
	PrintValue(head,25);
	cout<<"3.输出第5个元素"<<endl;
	PrintNodeAtPosition(head,5);
	cout<<"4.在第 3 个元素前插入值为 98 的元素,然后输出链表"<<endl;
	Insert(head,3,98);
	PrintList(head);
	cout<<"5.输出删除第 4 个元素后的链表"<<endl;
	Delete(head,4);
	PrintList(head);
	return 0;
}

二、栈和队列😘

顺序栈

1、建立顺序栈
// 建立顺序栈
struct Stack {
    int *elem; // 指向动态分配的数组
    int top; // 栈顶指针
    int MaxSize; // 栈的最大容量
};

// 创建栈
Stack* CreateStack(int MaxSize) {
    Stack* stack = new Stack();
    stack->elem = new int[MaxSize];
    stack->top = -1;
    stack->MaxSize = MaxSize;
    return stack;
}
2、入栈
// 入栈
void Push(Stack* stack, int val) {
    if (stack->top < stack->MaxSize - 1) { // 如果栈未满
        stack->elem[++stack->top] = val; // 栈顶指针后移并赋值
    } else {
        cout << "栈已满,无法入栈" << endl;
    }
}
3、出栈
// 出栈
int Pop(Stack* stack) {
    if (stack->top >= 0) { // 如果栈非空
        return stack->elem[stack->top--]; // 返回栈顶元素并移动栈顶指针
    } else {
        cout << "栈为空,无法出栈" << endl;
        return -1; // 返回-1表示栈空
    }
}
4、取栈顶
// 取栈顶
int GetTop(Stack* stack) {
    if (stack->top >= 0) { // 如果栈非空
        return stack->elem[stack->top]; // 返回栈顶元素
    } else {
        cout << "栈为空,无法获取栈顶元素。" << endl;
        return -1; // 返回-1表示栈空
    }
}
5、遍历栈
// 遍历栈
void TraverseStack(Stack* stack) {
        for (int i = 0; i <= stack->top; i++) {
            cout << stack->elem[i] << " ";
        }
        cout << endl;
}
6、判栈空
// 判断栈是否为空
bool IsEmpty(Stack* stack) {
    return stack->top < 0; // 如果栈顶指针小于0,则栈为空
}
实现: 
#include <iostream>
#include <vector>
using namespace std;

// 建立顺序栈
struct Stack {
    int *elem; // 指向动态分配的数组
    int top; // 栈顶指针
    int MaxSize; // 栈的最大容量
};

// 创建栈
Stack* CreateStack(int MaxSize) {
    Stack* stack = new Stack();
    stack->elem = new int[MaxSize];
    stack->top = -1;
    stack->MaxSize = MaxSize;
    return stack;
}

// 入栈
void Push(Stack* stack, int val) {
    if (stack->top < stack->MaxSize - 1) { // 如果栈未满
        stack->elem[++stack->top] = val; // 栈顶指针后移并赋值
    } else {
        cout << "栈已满,无法入栈" << endl;
    }
}

// 出栈
int Pop(Stack* stack) {
    if (stack->top >= 0) { // 如果栈非空
        return stack->elem[stack->top--]; // 返回栈顶元素并移动栈顶指针
    } else {
        cout << "栈为空,无法出栈" << endl;
        return -1; // 返回-1表示栈空
    }
}

// 取栈顶
int GetTop(Stack* stack) {
    if (stack->top >= 0) { // 如果栈非空
        return stack->elem[stack->top]; // 返回栈顶元素
    } else {
        cout << "栈为空,无法获取栈顶元素。" << endl;
        return -1; // 返回-1表示栈空
    }
}

// 遍历栈
void TraverseStack(Stack* stack) {
        for (int i = 0; i <= stack->top; i++) {
            cout << stack->elem[i] << " ";
        }
        cout << endl;
}

// 判断栈是否为空
bool IsEmpty(Stack* stack) {
    return stack->top < 0; // 如果栈顶指针小于0,则栈为空
}

// 从输入读取元素并添加
void ReadInputToStack(Stack* stack) {
    cout << "请输入你需要建立的初始顺序栈(只允许实数):" << endl;
    vector<double> Arr;
    double input;
    while (cin >> input) {
        Arr.push_back(input);
        if (cin.peek() == '\n') {
            cin.ignore();
            break;
        }
    }
    int index = 0;
    for (double value : Arr) { // 遍历Arr而不是stack
        Push(stack, static_cast<int>(value));
    }
}

int main() {
    int max = 0;
    cout << "请输入栈的最大容量:" << endl;
    cin >> max;
    Stack* stack = CreateStack(max);
    ReadInputToStack(stack);
    TraverseStack(stack);
    return 0;
}

链栈

1、建立链栈
// 定义链栈节点结构体
struct StackNode {
    int val;
    StackNode* next;
};

// 创建链栈
StackNode* CreateStack() {
    StackNode* head = new StackNode(); // 创建头节点
    head->next = nullptr;
    return head;
}
2、入栈
// 入栈操作
void Push(StackNode* head, int val) {
    StackNode* newNode = new StackNode{val, nullptr}; // 创建新节点
    newNode->next = head->next; // 将新节点链接到链表
    head->next = newNode; // 头节点指向新节点
}
3、出栈
// 出栈操作
int Pop(StackNode* head) {
    if (head->next == nullptr) {
        cout << "栈为空,无法出栈。" << endl;
        return -1; // 返回-1表示栈空
    }
    StackNode* temp = head->next; // 临时节点
    int val = temp->val; // 保存要返回的值
    head->next = temp->next; // 头节点指向下一个节点
    delete temp; // 释放临时节点
    return val; // 返回栈顶元素
}
4、取栈顶
// 获取栈顶元素
int GetTop(StackNode* head) {
    if (head->next == nullptr) {
        cout << "栈为空,无法获取栈顶元素。" << endl;
        return -1; // 返回-1表示栈空
    }
    return head->next->val; // 返回栈顶元素
}
5、遍历栈
// 遍历链栈
void TraverseStack(StackNode* head) {
    if (head->next == nullptr) {
        cout << "栈为空。" << endl;
        return;
    }
    StackNode* current = head->next; // 从栈顶开始遍历
    cout << "链栈元素: ";
    while (current != nullptr) {
        cout << current->val << " ";
        current = current->next; // 移动到下一个节点
    }
    cout << endl;
}
6、判栈空
// 判断栈是否为空
bool IsEmpty(StackNode* head) {
    return head->next == nullptr; // 如果头节点的next指针为空,则栈为空
}
实现: 
#include<iostream>
using namespace std;

// 定义链栈节点结构体
struct StackNode {
    int val;
    StackNode* next;
};

// 创建链栈
StackNode* CreateStack() {
    StackNode* head = new StackNode(); // 创建头节点
    head->next = nullptr;
    return head;
}

// 入栈操作
void Push(StackNode* head, int val) {
    StackNode* newNode = new StackNode{val, nullptr}; // 创建新节点
    newNode->next = head->next; // 将新节点链接到链表
    head->next = newNode; // 头节点指向新节点
}

// 出栈操作
int Pop(StackNode* head) {
    if (head->next == nullptr) {
        cout << "栈为空,无法出栈。" << endl;
        return -1; // 返回-1表示栈空
    }
    StackNode* temp = head->next; // 临时节点
    int val = temp->val; // 保存要返回的值
    head->next = temp->next; // 头节点指向下一个节点
    delete temp; // 释放临时节点
    return val; // 返回栈顶元素
}

// 遍历链栈
void TraverseStack(StackNode* head) {
    if (head->next == nullptr) {
        cout << "栈为空。" << endl;
        return;
    }
    StackNode* current = head->next; // 从栈顶开始遍历
    cout << "链栈元素: ";
    while (current != nullptr) {
        cout << current->val << " ";
        current = current->next; // 移动到下一个节点
    }
    cout << endl;
}

// 获取栈顶元素
int GetTop(StackNode* head) {
    if (head->next == nullptr) {
        cout << "栈为空,无法获取栈顶元素。" << endl;
        return -1; // 返回-1表示栈空
    }
    return head->next->val; // 返回栈顶元素
}

// 判断栈是否为空
bool IsEmpty(StackNode* head) {
    return head->next == nullptr; // 如果头节点的next指针为空,则栈为空
}

int main() {
    StackNode* stack = CreateStack(); // 创建链栈
    
    cout << "入栈元素: 10, 20, 30, 40, 50" << endl;
    Push(stack, 10);
    Push(stack, 20);
    Push(stack, 30);
    Push(stack, 40);
    Push(stack, 50);
    
    cout << "栈顶元素: " << GetTop(stack) << endl;
    cout << "出栈元素: " << Pop(stack) << endl;
    cout << "栈顶元素: " << GetTop(stack) << endl;
    
    TraverseStack(stack); // 调用遍历链栈的方法
    
    cout << "栈是否为空: " << (IsEmpty(stack) ? "是" : "否") << endl;
    
    return 0;
}

队列

顺序队列

1、建立顺序队列
// 定义队列结构体
struct Queue {
    vector<int> elements; // 使用vector来存储队列元素
};

// 创建队列
Queue* CreateQueue() {
    return new Queue(); // 创建队列对象
}
2、入队
// 入队操作
void Enqueue(Queue* queue, int val) {
    queue->elements.push_back(val); // 将元素添加到队列末尾
}
3、出队
// 出队操作
int Dequeue(Queue* queue) {
    if (queue->elements.empty()) { // 如果队列为空
        cout << "队列为空,无法出队。" << endl;
        return -1; // 返回-1表示队空
    }
    int val = queue->elements.front(); // 获取队首元素
    queue->elements.erase(queue->elements.begin()); // 删除队首元素
    return val; // 返回队首元素
}
4、求队列长度
int GetQueueLength(Queue* queue) {
    return queue->elements.size(); // 返回队列中元素的数量
}
5、遍历队列
// 遍历队列
void TraverseQueue(Queue* queue) {
    if (queue->elements.empty()) { // 如果队列为空
        cout << "队列为空。" << endl;
        return;
    }
    cout << "队列元素: ";
    for (int val : queue->elements) {
        cout << val << " ";
    }
    cout << endl;
}
实现:
#include<iostream>
#include<vector>
using namespace std;

// 定义队列结构体
struct Queue {
    vector<int> elements; // 使用vector来存储队列元素
};

// 创建队列
Queue* CreateQueue() {
    return new Queue(); // 创建队列对象
}

// 入队操作
void Enqueue(Queue* queue, int val) {
    queue->elements.push_back(val); // 将元素添加到队列末尾
}

// 出队操作
int Dequeue(Queue* queue) {
    if (queue->elements.empty()) { // 如果队列为空
        cout << "队列为空,无法出队。" << endl;
        return -1; // 返回-1表示队空
    }
    int val = queue->elements.front(); // 获取队首元素
    queue->elements.erase(queue->elements.begin()); // 删除队首元素
    return val; // 返回队首元素
}

// 获取队列长度
int GetQueueLength(Queue* queue) {
    return queue->elements.size(); // 返回队列中元素的数量
}

// 遍历队列
void TraverseQueue(Queue* queue) {
    if (queue->elements.empty()) { // 如果队列为空
        cout << "队列为空。" << endl;
        return;
    }
    cout << "队列元素: ";
    for (int val : queue->elements) {
        cout << val << " ";
    }
    cout << endl;
}

// 获取队首元素
int GetFront(Queue* queue) {
    if (queue->elements.empty()) { // 如果队列为空
        cout << "队列为空,无法获取队首元素。" << endl;
        return -1; // 返回-1表示队空
    }
    return queue->elements.front(); // 返回队首元素
}

// 判断队列是否为空
bool IsEmpty(Queue* queue) {
    return queue->elements.empty(); // 如果队列大小为0,则队列为空
}

int main() {
    Queue* queue = CreateQueue(); // 创建队列
    
    cout << "入队元素: 10, 20, 30, 40, 50" << endl;
    Enqueue(queue, 10);
    Enqueue(queue, 20);
    Enqueue(queue, 30);
    Enqueue(queue, 40);
    Enqueue(queue, 50);
    
    TraverseQueue(queue); // 遍历队列
    
    cout << "队列长度: " << GetQueueLength(queue) << endl;
    
    cout << "队首元素: " << GetFront(queue) << endl;
    cout << "出队元素: " << Dequeue(queue) << endl;
    cout << "队首元素: " << GetFront(queue) << endl;
    
    cout << "队列是否为空: " << (IsEmpty(queue) ? "是" : "否") << endl;
    
    return 0;
}

链式队列

1、建立链式队列
// 定义链队列节点结构体
struct QueueNode {
    int val;
    QueueNode* next;
};

// 创建链队列
QueueNode* CreateQueue() {
    QueueNode* head = new QueueNode(); // 创建头节点
    head->next = nullptr;
    return head;
}
2、入队
// 入队操作
void Enqueue(QueueNode* head, int val) {
    QueueNode* newNode = new QueueNode{val, nullptr}; // 创建新节点
    newNode->next = head->next; // 将新节点链接到链表
    head->next = newNode; // 头节点指向新节点
}
3、出队
// 出队操作
int Dequeue(QueueNode* head) {
    if (head->next == nullptr) {
        cout << "队列为空,无法出队。" << endl;
        return -1; // 返回-1表示队空
    }
    QueueNode* temp = head->next; // 临时节点
    int val = temp->val; // 保存要返回的值
    head->next = temp->next; // 头节点指向下一个节点
    delete temp; // 释放临时节点
    return val; // 返回队首元素
}
4、求队列长度
// 获取队列长度
int GetQueueLength(QueueNode* head) {
    int length = 0;
    QueueNode* current = head->next;
    while (current != nullptr) {
        length++; // 计算队列中元素的数量
        current = current->next;
    }
    return length;
}
5、遍历队列
// 遍历队列
void TraverseQueue(QueueNode* head) {
    if (head->next == nullptr) { // 如果队列为空
        cout << "队列为空。" << endl;
        return;
    }
    QueueNode* current = head->next;
    cout << "队列元素: ";
    while (current != nullptr) {
        cout << current->val << " ";
        current = current->next; // 移动到下一个节点
    }
    cout << endl;
}
实现:
#include<iostream>
using namespace std;

// 定义链队列节点结构体
struct QueueNode {
    int val;
    QueueNode* next;
};

// 创建链队列
QueueNode* CreateQueue() {
    QueueNode* head = new QueueNode(); // 创建头节点
    head->next = nullptr;
    return head;
}

// 入队操作
void Enqueue(QueueNode* head, int val) {
    QueueNode* newNode = new QueueNode{val, nullptr}; // 创建新节点
    QueueNode* current = head;
    while (current->next != nullptr) {
        current = current->next; // 移动到链表末尾
    }
    current->next = newNode; // 将新节点链接到链表末尾
}

// 出队操作
int Dequeue(QueueNode* head) {
    if (head->next == nullptr) {
        cout << "队列为空,无法出队。" << endl;
        return -1; // 返回-1表示队空
    }
    QueueNode* temp = head->next; // 临时节点
    int val = temp->val; // 保存要返回的值
    head->next = temp->next; // 头节点指向下一个节点
    delete temp; // 释放临时节点
    return val; // 返回队首元素
}

// 获取队列长度
int GetQueueLength(QueueNode* head) {
    int length = 0;
    QueueNode* current = head->next;
    while (current != nullptr) {
        length++; // 计算队列中元素的数量
        current = current->next;
    }
    return length;
}

// 遍历队列
void TraverseQueue(QueueNode* head) {
    if (head->next == nullptr) { // 如果队列为空
        cout << "队列为空。" << endl;
        return;
    }
    QueueNode* current = head->next;
    cout << "队列元素: ";
    while (current != nullptr) {
        cout << current->val << " ";
        current = current->next; // 移动到下一个节点
    }
    cout << endl;
}

// 获取队首元素
int GetFront(QueueNode* head) {
    if (head->next == nullptr) {
        cout << "队列为空,无法获取队首元素。" << endl;
        return -1; // 返回-1表示队空
    }
    return head->next->val; // 返回队首元素
}

// 判断队列是否为空
bool IsEmpty(QueueNode* head) {
    return head->next == nullptr; // 如果头节点的next指针为空,则队列空
}

int main() {
    QueueNode* queue = CreateQueue(); // 创建链队列
    
    cout << "入队元素: 10, 20, 30, 40, 50" << endl;
    Enqueue(queue, 10);
    Enqueue(queue, 20);
    Enqueue(queue, 30);
    Enqueue(queue, 40);
    Enqueue(queue, 50);
    
    TraverseQueue(queue); // 遍历队列
    
    cout << "队列长度: " << GetQueueLength(queue) << endl;
    
    cout << "队首元素: " << GetFront(queue) << endl;
    cout << "出队元素: " << Dequeue(queue) << endl;
    cout << "队首元素: " << GetFront(queue) << endl;
    
    cout << "队列是否为空: " << (IsEmpty(queue) ? "是" : "否") << endl;
    
    return 0;
}

 三、树和二叉树

 

实现:

#include<iostream>
using namespace std;

// 结构体
struct Bittree {
    char data;
    Bittree *lchild;
    Bittree *rchild;
};

// 先序构建二叉树
Bittree* Creat() {
    char n;
    scanf(" %c", &n); // 注意在%c前加空格,以跳过任何前导空白
    if (n == '#') {
        return NULL;
    } else {
        Bittree* T = new Bittree();
        T->data = n;
        T->lchild = Creat();
        T->rchild = Creat();
        return T;
    }
}

// 先序遍历
void PreOrder(Bittree *T) {
    if (T) {
        printf("%2c", T->data);
        PreOrder(T->lchild);
        PreOrder(T->rchild);
    }
}

// 中序遍历
void InOrder(Bittree *T) {
    if (T) {
        InOrder(T->lchild);
        printf("%2c", T->data);
        InOrder(T->rchild);
    }
}

// 后序遍历
void PostOrder(Bittree *T) {
    if (T) {
        PostOrder(T->lchild);
        PostOrder(T->rchild);
        printf("%2c", T->data);
    }
}

// 统计叶子结点的个数
int Leaf(Bittree *T) {
    int LeafCount;
    if (T == NULL)
        LeafCount = 0;
    else if (T->lchild == NULL && T->rchild == NULL)
        LeafCount = 1;
    else
        LeafCount = Leaf(T->lchild) + Leaf(T->rchild);
    return LeafCount;
}

// 计算二叉树的深度
int TreeDepth(Bittree *T) {
    if (T == NULL)
        return 0;
    else {
        int depthleft = TreeDepth(T->lchild) + 1;
        int depthright = TreeDepth(T->rchild) + 1;
        return depthleft > depthright ? depthleft : depthright;
    }
}

int main() {
    printf("先序构造一颗二叉树(左/右孩子为空用'#'表示):");
    Bittree *T = Creat();
    printf("此二叉树的先序遍历序列是:");
    PreOrder(T);
    printf("\n");
    printf("此二叉树的中序遍历序列是:");
    InOrder(T);
    printf("\n");
    printf("此二叉树的后序遍历序列是:");
    PostOrder(T);
    printf("\n");
    printf("这棵树叶子结点有%d个\n", Leaf(T));
    printf("这棵树的深度为:%d\n", TreeDepth(T));
    system("pause");
    return 0;
}

 四、图

实现:

#include<iostream>
#include<stack> // 引入栈头文件
using namespace std;
#define MAX_NUM 100

// 定义邻接矩阵
struct Graph{
    int MaxArr[MAX_NUM][MAX_NUM];
    int num;
}; 

// 初始化图
Graph* create(int n){
    Graph* graph=new Graph();
    graph->num=n;
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            graph->MaxArr[i][j]=0;
        }
    }
    return graph;
} 

// 添加单向边
void addEdge(Graph* graph,int src,int dest){
    graph->MaxArr[src][dest]=1;
} 

// 广度优先搜索
bool bfs(Graph* graph,int start,int end,int* parent){
    int visited[MAX_NUM];
    bool inQueue[MAX_NUM];
    int queue[MAX_NUM];
    int front=0,rear=0;
    
    for(int i=0;i<graph->num;i++){
        visited[i]=false;
        inQueue[i]=false;
        parent[i]=-1;
    }
    
    queue[rear++]=start;
    inQueue[start]=true;
    visited[start]=true;
    
    while(front<rear){
        int current=queue[front++];
        for(int i=0;i<graph->num;i++){
            if(!visited[i]&&graph->MaxArr[current][i]==1){
                queue[rear++]=i;
                inQueue[i]=true;
                visited[i]=true;
                parent[i]=current;
            }
        }
    }
    return visited[end];
} 

// 输出路径
void printPath(int* parent,int end){
    printf("Path from start to %d: ", end);
    if(parent[end]==-1){
        printf("There is no path\n");
        return;
    }
    stack<int> path; // 使用栈来存储路径
    int current = end;
    while(current != -1) {
        path.push(current); // 将节点压入栈中
        current = parent[current];
    }
    // 逐个弹出栈中的元素以实现倒序输出
    while(!path.empty()) {
        printf("%d ", path.top());
        path.pop();
        if(!path.empty()) {
            printf("-> ");
        }
    }
    printf("\n");
} 

int main(){
    int Num,start,end;
    printf("输入结点个数:");
    scanf("%d",&Num);
    Graph* graph=create(Num);
    
    printf("输入边(以'src dest'形式,输入0 0结束):");
    int src,dest;
    while(true){
        cin >> src >> dest;
        if(src == 0 && dest == 0) break; // 如果输入是0 0,则结束循环
        addEdge(graph,src,dest);
    }
    
    printf("输入起点:");
    scanf("%d",&start);
    
    printf("输入终点:");
    scanf("%d",&end);
    
    int* parent=(int*)malloc(Num*sizeof(int));
    if(bfs(graph,start,end,parent)){
        printPath(parent,end);
    }else{
        printf("There is no path\n");
    }
    
    free(parent);
    delete graph;
    return 0;
}

 

五、查找和排序

 折半查找实现:

#include <stdio.h>

// 折半查找函数
int binarySearch(int arr[], int l, int r, int x) {
    if (r >= l) {
        int mid = l + (r - l) / 2;

        // 如果中间元素正好是要找的值,返回索引
        if (arr[mid] == x)
            return mid;

        // 如果中间元素比要找的值小,在右半部分继续查找
        if (arr[mid] < x)
            return binarySearch(arr, mid + 1, r, x);

        // 如果中间元素比要找的值大,在左半部分继续查找
        return binarySearch(arr, l, mid - 1, x);
    }

    // 如果数组中没有找到值,返回-1
    return -1;
}

int main() {
    int arr[] = {12, 23, 28, 35, 37, 39, 50, 60, 78, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    int x;

    printf("输入待查找记录:");
    scanf("%d", &x);

    int result = binarySearch(arr, 0, n - 1, x);

    if (result == -1)
        printf("该记录不存在。\n");
    else
        printf("该记录在表中位置 %d。\n", result);

    return 0;
}

快速排序实现: 

#include <stdio.h>
int partition(int arr[], int low, int high);
void swap(int *xp, int *yp);

// 快速排序函数
void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);

        // 递归排序左半部分
        quickSort(arr, low, pi - 1);

        // 递归排序右半部分
        quickSort(arr, pi + 1, high);
    }
}

// 用于快速排序的辅助函数,用于分区
int partition(int arr[], int low, int high) {
    int pivot = arr[high]; // 选择最后一个元素作为基准
    int i = (low - 1); // 初始化指向比基准小的元素的指针

    for (int j = low; j <= high - 1; j++) {
        // 如果当前元素小于或等于基准,则交换元素
        if (arr[j] <= pivot) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]); // 将基准元素放在正确的位置
    return (i + 1);
}

// 交换两个元素
void swap(int *xp, int *yp) {
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

int main() {
    int arr[] = {12, 23, 28, 35, 37, 39, 50, 60, 78, 90};
    int n = sizeof(arr) / sizeof(arr[0]);

    quickSort(arr, 0, n - 1);

    printf("排序后的数组:\n");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);

    return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1801230.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

LeetCode | 1470.重新排列数组

class Solution(object):def shuffle(self, nums, n):""":type nums: List[int]:type n: int:rtype: List[int]"""result []for i in range(n):result.append(nums[i])result.append(nums[i n])return result这题很容易想到的就是遍历整个数组…

HQL面试题练习 —— 累加刚好超过各省GDP40%的地市名称

目录 1 题目2 建表语句3 题解 1 题目 现有各省地级市的gdp数据&#xff0c;求从高到底累加刚好超过各省GDP40%的地市名称&#xff0c;临界地市也需要。例如&#xff1a; 浙江省的杭州24% 宁波 20% ,杭州宁波44% 大于40% 取出杭州、宁波 江苏省的苏州19% 南京 14% 无锡 12%&am…

天行健咨询 | 谢宁DOE培训的课程内容有哪些?

谢宁DOE培训的课程内容丰富而深入&#xff0c;旨在帮助学员掌握谢宁问题解决方法在质量管理中的重要作用&#xff0c;并学会如何运用这一方法工具&#xff0c;在不中断生产过程的前提下&#xff0c;找出并解决生产中遇到的复杂而顽固的问题。 首先&#xff0c;课程会详细介绍谢…

国产神器,这个太强悍了 !

自从 ChatGPT 火了以后&#xff0c;国内的 AI 大模型也是越来越多&#xff0c;各家都有不同的侧重点&#xff0c;其中&#xff0c;咱们国家队的代表就是阿里的通义千问了。就在今天&#xff0c;通义千问推出了第二代开源模型系列Qwen2&#xff0c;下面跟大家重点介绍一下这个新…

【面试干货】索引的优缺点

【面试干货】索引的优缺点 1、创建索引可以大大提高系统的性能&#xff08;**优点**&#xff09;2、增加索引也有许多不利的方面&#xff08;**缺点**&#xff09; &#x1f496;The Begin&#x1f496;点点关注&#xff0c;收藏不迷路&#x1f496; 1、创建索引可以大大提高系…

mac无法读取windows分区怎么办 苹果硬盘怎么读取

对于Mac电脑用户但有Windows系统使用需求的&#xff0c;我们可以通过Boot Camp启动转换助理安装Windows分区这个方案来解决&#xff0c;不过因为两个系统的磁盘格式不同&#xff0c;相应的也会产生一些问题&#xff0c;例如无法正常读取windows分区。下面本文就详细说明mac无法…

前端三大件速成 05 javascript(1)js组成、引入、基本语法

文章目录 一、js组成二、js的引入三、基本语法1、变量2、基本规范3、关键字4、数据类型&#xff08;1&#xff09;基本数据类型&#xff08;2&#xff09;引用数据类型&#xff08;3&#xff09;数据类型转换&#xff08;4&#xff09;typeof运算符 5、运算符6、流程控制&#…

优化扩散模型中的采样计划

在生成模型领域&#xff0c;扩散模型&#xff08;Diffusion Models, DMs&#xff09;因其卓越的生成质量而成为最新的技术趋势。但这些模型的一个关键缺点是它们的采样速度较慢&#xff0c;需要通过大型神经网络进行多次顺序函数评估。扩散模型通过一个称为采样计划的离散噪声水…

Elastic Search(ES)Java 入门实操(2)搜索代码

上篇解释了 ES 的基本概念和分词器。Elastic Search &#xff08;ES&#xff09;Java 入门实操&#xff08;1&#xff09;下载安装、概念-CSDN博客 Elastic Search&#xff08;ES&#xff09;Java 入门实操&#xff08;3&#xff09;数据同步-CSDN博客 这篇主要演示 Java 整合…

Day 42 LVS四层负载均衡

一&#xff1a;负载均衡简介 1.集群是什么 ​ 集群&#xff08;cluster&#xff09;技术是一种较新的技术&#xff0c;通过集群技术&#xff0c;可以在付出较低成本的情况下获得在性能、可靠性、灵活性方面的相对较高的收益&#xff0c;其任务调度则是集群系统中的核心技术 …

PyTorch深度学习实战(44)——基于 DETR 实现目标检测

PyTorch深度学习实战&#xff08;44&#xff09;——基于 DETR 实现目标检测 0. 前言1. Transformer1.1 Transformer 基础1.2 Transformer 架构 2. DETR2.1 DETR 架构2.2 实现 DETR 模型 3. 基于 DETR 实现目标检测3.1 数据加载与模型构建3.2 模型训练与测试 小结系列链接 0. 前…

windows安装tensorboard

要在Windows系统上使用TensorBoard来可视化你的TensorFlow模型训练过程&#xff0c;请按照以下步骤进行操作&#xff1a; 安装TensorFlow和TensorBoard 安装Python&#xff1a; 确保你已经安装了Python。你可以从Python官方网站下载并安装最新版本的Python。 安装TensorFlow&…

kafka-重试和死信主题(SpringBoot整合Kafka)

文章目录 1、重试和死信主题2、死信队列3、代码演示3.1、appication.yml3.2、引入spring-kafka依赖3.3、创建SpringBoot启动类3.4、创建生产者发送消息3.5、创建消费者消费消息 1、重试和死信主题 kafka默认支持重试和死信主题 重试主题&#xff1a;当消费者消费消息异常时&…

基于思通数科大模型的设备隐患智能检测:图像处理与声音分析的融合应用

在现代工业生产中&#xff0c;设备的稳定运行对保障生产效率和产品质量至关重要。然而&#xff0c;设备的老化、磨损以及异常状态的检测往往需要大量的人力和物力。思通数科大模型结合图像处理技术和声音分析技术&#xff0c;为设备隐患检测提供了一种自动化、高效的解决方案。…

源码、反码和补码

对于有符号数而言&#xff0c;原码就是一个数的二进制表示。二进制的最高位是符号位&#xff0c;0 表示正数&#xff0c;1 表示负数。 计算机用数的原码进行显示&#xff0c;数的计算和存储是用补码进行的。 正数的原码&#xff0c;反码和补码都一样&#xff0c;即正数三码合…

Matching Anything by Segmenting Anything

摘要 在复杂场景中跨视频帧稳健地关联相同对象是许多应用的关键&#xff0c;特别是多目标跟踪&#xff08;MOT&#xff09;。当前方法主要依赖于标注的特定领域视频数据集&#xff0c;这限制了学习到的相似度嵌入的跨域泛化能力。我们提出了MASA&#xff0c;一种新颖的方法用于…

JavaScript 动态网页实例 —— 图像显示

图像是网页设计中必不可少的内容之一,而图像的显示方式更是关系到网站的第一印象。本章介绍图像的显示,主要包括:图片的随机显示、图像的显示和隐藏、图像的滚动显示、图像的探照灯扫描显示、多幅图像的翻页显示、图像的水纹效果显示、全景图效果显示手电照射效果显示以及雷达…

揭秘800G以太网——简介

什么是800G以太网&#xff1f; 800G以太网是一种高带宽以太网标准&#xff0c;每秒可传输800 Gbps&#xff08;千兆位每秒&#xff09;的数据速率。它代表了以太网技术的又一进步&#xff0c;旨在满足不断增长的数据传输需求以及处理大量数据的能力。因此&#xff0c;800G以太…

杰理AC632N提升edr的hid传输速率, 安卓绝对坐标触摸点被识别成鼠标的修改方法

第一个问题: 首先修改edr的hid传输速率.修改你的板级配置,里面的一个地方给注释掉了,请打开那个注释就能提升edr的hid传输效率了 第二个问题: 修改632n系别把触摸板的hid报告描述符识别成鼠标点,修改如下: 注释掉上面的pnp,改成下面的

RocketMQ的安装

首先到RocketMQ官网下载页面下载 | RocketMQ (apache.org)&#xff0c;本机解压缩&#xff0c;作者在这里用的是最新的5.2.0版本。按照如下步骤安装。 1、环境变量配置rocket mq地址 ROCKETMQ_HOME D:\rocketmq-all-5.2.0-bin-release 在变量path中添加”%ROCKETMQ_HOME%\bi…