1. 前言
《数据结构C语言版第二版》是计算机科学领域经典教材之一,由严蔚敏、吴伟民编著。本书以C语言为工具,详细介绍了各种数据结构及其算法实现。为了帮助读者更好地理解和掌握书中内容,以下是对课后习题的详细解答指南。
2. 线性表
2.1 习题一:顺序表的创建
题目描述:编写一个函数,实现顺序表的创建。
解答:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int length;
} SeqList;
SeqList* createSeqList() {
SeqList *list = (SeqList*)malloc(sizeof(SeqList));
if (list == NULL) {
printf("内存分配失败!\n");
exit(1);
}
list->length = 0;
return list;
}
2.2 习题二:顺序表的插入
题目描述:编写一个函数,实现顺序表的插入操作。
解答:
int insertSeqList(SeqList *list, int i, int e) {
if (i < 1 || i > list->length + 1 || list->length == MAXSIZE) {
return 0;
}
for (int j = list->length; j >= i; j--) {
list->data[j] = list->data[j - 1];
}
list->data[i - 1] = e;
list->length++;
return 1;
}
3. 链表
3.1 习题一:单链表的创建
题目描述:编写一个函数,实现单链表的创建。
解答:
typedef struct Node {
int data;
struct Node *next;
} Node;
Node* createList() {
Node *head = (Node*)malloc(sizeof(Node));
if (head == NULL) {
printf("内存分配失败!\n");
exit(1);
}
head->next = NULL;
return head;
}
3.2 习题二:单链表的插入
题目描述:编写一个函数,实现单链表的插入操作。
解答:
Node* insertList(Node *head, int i, int e) {
if (i < 1 || head == NULL) {
return NULL;
}
Node *p = head;
int j = 1;
while (p->next != NULL && j < i - 1) {
p = p->next;
j++;
}
Node *newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("内存分配失败!\n");
exit(1);
}
newNode->data = e;
newNode->next = p->next;
p->next = newNode;
return head;
}
4. 栈和队列
4.1 习题一:栈的创建
题目描述:编写一个函数,实现栈的创建。
解答:
typedef struct {
int data[MAXSIZE];
int top;
} Stack;
Stack* createStack() {
Stack *stack = (Stack*)malloc(sizeof(Stack));
if (stack == NULL) {
printf("内存分配失败!\n");
exit(1);
}
stack->top = -1;
return stack;
}
4.2 习题二:栈的入栈操作
题目描述:编写一个函数,实现栈的入栈操作。
解答:
int push(Stack *stack, int e) {
if (stack->top == MAXSIZE - 1) {
return 0;
}
stack->data[++stack->top] = e;
return 1;
}
5. 树和图
5.1 习题一:二叉树的创建
题目描述:编写一个函数,实现二叉树的创建。
解答:
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* createTree() {
TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode));
if (root == NULL) {
printf("内存分配失败!\n");
exit(1);
}
root->data = 0;
root->left = NULL;
root->right = NULL;
return root;
}
5.2 习题二:二叉树的遍历
题目描述:编写一个函数,实现二叉树的先序遍历。
解答:
void preOrder(TreeNode *root) {
if (root == NULL) {
return;
}
printf("%d ", root->data);
preOrder(root->left);
preOrder(root->right);
}
6. 总结
本文对《数据结构C语言版第二版》课后习题进行了详细的解答。通过这些习题的练习,读者可以更好地掌握数据结构的相关知识。在实际编程过程中,可以根据具体情况选择合适的数据结构,提高程序的性能和可维护性。
