c语言写对链式线性表进行初始化和销毁操作,以及对输入参数进行合法性检查
时间: 2023-05-20 21:00:47 浏览: 148
链式线性表的初始化操作可以通过以下代码实现:
```
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct List {
Node *head;
int length;
} List;
void initList(List *list) {
list->head = NULL;
list->length = 0;
}
```
链式线性表的销毁操作可以通过以下代码实现:
```
void destroyList(List *list) {
Node *p = list->head;
while (p != NULL) {
Node *temp = p;
p = p->next;
free(temp);
}
list->head = NULL;
list->length = 0;
}
```
对输入参数进行合法性检查可以通过以下代码实现:
```
void insert(List *list, int index, int data) {
if (index < 0 || index > list->length) {
printf("Error: index out of range\n");
return;
}
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
if (index == 0) {
newNode->next = list->head;
list->head = newNode;
} else {
Node *p = list->head;
for (int i = 0; i < index - 1; i++) {
p = p->next;
}
newNode->next = p->next;
p->next = newNode;
}
list->length++;
}
```
注意:以上代码仅供参考,具体实现可能会因为具体情况而有所不同。
阅读全文