请列举5个C语言关于指针高难度笔试考察题目,请用代码举例并写上注释说明
时间: 2024-05-01 13:21:20 浏览: 98
c语言指针习题
5星 · 资源好评率100%
1. 如何用指针实现一个字符串反转的函数?
```c
void reverse_str(char *str) {
char *left = str; // 左指针指向字符串首地址
char *right = str + strlen(str) - 1; // 右指针指向字符串末尾
while (left < right) {
char temp = *left;
*left++ = *right;
*right-- = temp;
}
}
```
2. 如何用指针实现一个快速排序算法?
```c
void quick_sort(int *arr, int left, int right) {
if (left >= right) return;
int i = left;
int j = right;
int pivot = *(arr + left);
while (i < j) {
while (i < j && *(arr + j) >= pivot) j--;
*(arr + i) = *(arr + j);
while (i < j && *(arr + i) <= pivot) i++;
*(arr + j) = *(arr + i);
}
*(arr + i) = pivot;
quick_sort(arr, left, i - 1);
quick_sort(arr, i + 1, right);
}
```
3. 如何用指针实现一个链表的反转?
```c
typedef struct Node {
int val;
struct Node *next;
} Node;
Node* reverse_list(Node *head) {
Node *prev = NULL;
Node *curr = head;
while (curr) {
Node *temp = curr->next;
curr->next = prev;
prev = curr;
curr = temp;
}
return prev;
}
```
4. 如何用指针实现一个二叉树的中序遍历?
```c
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
void inorder_traversal(TreeNode *root) {
if (!root) return;
TreeNode *stack[100]; // 定义一个存放节点指针的栈
int top = -1; // 栈顶指针
while (root || top != -1) {
while (root) {
stack[++top] = root;
root = root->left;
}
root = stack[top--];
printf("%d ", root->val);
root = root->right;
}
}
```
5. 如何用指针实现一个矩阵的转置?
```c
void transpose_matrix(int *matrix, int row, int col) {
int temp;
for (int i = 0; i < row; i++) {
for (int j = i + 1; j < col; j++) {
temp = *(matrix + i * col + j);
*(matrix + i * col + j) = *(matrix + j * col + i);
*(matrix + j * col + i) = temp;
}
}
}
```
阅读全文