用C语言写出来:使用模块开发,创建一个链表(只包含一个int类型的链表),实现 1、创建一个空链表; 2、链表尾部添加元素; 3、链表遍历; 4、链表删除尾部元素; 5、链表修改特定元素; 6、链表查询特定元素。
时间: 2024-06-17 09:00:42 浏览: 10
好的,使用C语言实现一个包含一个int类型数据的链表,可以按照以下步骤:
1. 首先定义一个结构体作为链表的节点,每个节点包含一个整型变量和一个指向下一个节点的指针。
```
typedef struct node {
int data;
struct node *next;
}Node;
```
2. 定义一个全局变量,作为链表头节点的指针。
```
Node *head = NULL;
```
3. 实现链表创建函数,用于创建一个空链表。
```
void createList() {
head = NULL;
}
```
4. 实现链表尾部添加元素函数。
```
void addNode(int num) {
Node *newNode, *temp;
newNode = (Node*)malloc(sizeof(Node));
newNode->data = num;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
}
else {
temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
```
5. 实现链表遍历函数。
```
void traverseList() {
Node *temp;
if (head == NULL) {
printf("The list is empty.\n");
}
else {
temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
}
```
6. 实现链表删除尾部元素函数。
```
void deleteNode() {
Node *temp, *prev;
if (head == NULL) {
printf("The list is empty.\n");
}
else if (head->next == NULL) {
free(head);
head = NULL;
}
else {
temp = head;
prev = NULL;
while (temp->next != NULL) {
prev = temp;
temp = temp->next;
}
free(temp);
prev->next = NULL;
}
}
```
7. 实现链表修改特定元素函数。
```
void modifyNode(int oldNum, int newNum) {
Node *temp;
if (head == NULL) {
printf("The list is empty.\n");
}
else {
temp = head;
while (temp != NULL) {
if (temp->data == oldNum) {
temp->data = newNum;
printf("The element has been modified successfully.\n");
return;
}
temp = temp->next;
}
printf("The element is not found in the list.\n");
}
}
```
8. 实现链表查询特定元素函数。
```
void searchNode(int num) {
Node *temp;
if (head == NULL) {
printf("The list is empty.\n");
}
else {
temp = head;
while (temp != NULL) {
if (temp->data == num) {
printf("The element is found in the list.\n");
return;
}
temp = temp->next;
}
printf("The element is not found in the list.\n");
}
}
```
以上就是用C语言实现创建一个包含一个int类型的链表所需的函数。如果有任何问题,请随时提出。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![CPP](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)