CSDN编程题解答
CSDN编程题解答
作为一个程序员,经常在CSDN上看到各种编程题,下面我将为您解答一些常见的CSDN编程题:
单链表是一种常见的数据结构,可以通过定义一个节点结构体来实现。每个节点包含数据和指向下一个节点的指针。我们可以定义一个链表类,包含插入、删除、查找等操作。
```cpp
#include
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedList {
private:
Node* head;
public:
LinkedList() {
head = nullptr;
}
void insert(int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->next = head;
head = newNode;
}
void remove(int value) {
Node* current = head;
Node* prev = nullptr;
while (current != nullptr && current->data != value) {
prev = current;
current = current->next;
}
if (current == nullptr) {
cout << "Value not found in the list." << endl;
return;
}
if (prev == nullptr) {
head = current->next;
} else {
prev->next = current->next;
}
delete current;
}
void display() {
Node* current = head;
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
};
int main() {
LinkedList list;
list.insert(1);
list.insert(2);
list.insert(3);
list.display();
list.remove(2);
list.display();
return 0;
}
```
快速排序是一种高效的排序算法,通过选择一个基准值,将数组分为两部分,小于基准值的放在左边,大于基准值的放在右边,然后递归地对左右两部分进行排序。
```cpp
#include
#include
using namespace std;
int partition(vector& arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j ) {
if (arr[j] < pivot) {
i ;
swap(arr[i], arr[j]);
}
}
swap(arr[i 1], arr[high]);
return i 1;
}
void quickSort(vector& 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 main() {
vector arr = {12, 7, 11, 13, 5, 6};
int n = arr.size();
quickSort(arr, 0, n - 1);
for (int num : arr) {
cout << num << " ";
}
return 0;
}
```
通过使用Socket编程,我们可以实现一个简单的TCP服务器。服务器端需要创建Socket、绑定IP和端口、监听连接、接受客户端连接、收发数据等操作。
```cpp
#include
#include
#include
#include
#include
using namespace std;
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[1024] = {0};
string hello = "Hello from server";
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8080);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("Bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0) {
perror("Listen failed");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("Accept failed");
exit(EXIT_FAILURE);
}
int valread = read(new_socket, buffer, 1024);
cout << buffer << endl;
send(new_socket, hello.c_str(), hello.length(), 0);
cout << "Hello message sent" << endl;
return 0;
}
```
以上是对一些常见CSDN编程题的解答,希望对您有所帮助!