编写一个程序linklist.c,实现单链表L的基本运算
时间: 2023-04-03 14:00:55 浏览: 147
你好,我可以回答这个问题。以下是一个简单的单链表的基本运算的示例代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
typedef struct list {
Node *head;
int length;
} List;
void initList(List *L) {
L->head = NULL;
L->length = ;
}
void insert(List *L, int data) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = L->head;
L->head = newNode;
L->length++;
}
void delete(List *L, int data) {
Node *prev = NULL;
Node *curr = L->head;
while (curr != NULL && curr->data != data) {
prev = curr;
curr = curr->next;
}
if (curr != NULL) {
if (prev == NULL) {
L->head = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
L->length--;
}
}
void printList(List *L) {
Node *curr = L->head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
List L;
initList(&L);
insert(&L, 1);
insert(&L, 2);
insert(&L, 3);
printList(&L);
delete(&L, 2);
printList(&L);
return ;
}
相关推荐
![text/x-c](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)