C++ list的实现
时间: 2023-09-28 13:04:13 浏览: 82
c++list类实现
5星 · 资源好评率100%
C语言中可以通过结构体和指针实现链表,以下是一种简单的实现方式:
定义链表节点结构体:
```
typedef struct node {
int data; // 数据域
struct node* next; // 指针域
} Node;
```
定义链表结构体:
```
typedef struct {
Node* head; // 链表头节点
int size; // 链表长度
} List;
```
初始化链表:
```
List* initList() {
List* list = (List*)malloc(sizeof(List));
list->head = NULL;
list->size = 0;
return list;
}
```
插入节点:
```
void insertNode(List* list, int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
if (list->head == NULL) {
list->head = node;
} else {
Node* p = list->head;
while (p->next != NULL) {
p = p->next;
}
p->next = node;
}
list->size++;
}
```
删除节点:
```
void deleteNode(List* list, int data) {
Node* p = list->head;
Node* q = NULL;
while (p != NULL && p->data != data) {
q = p;
p = p->next;
}
if (p == NULL) {
return;
}
if (q == NULL) {
list->head = p->next;
} else {
q->next = p->next;
}
free(p);
list->size--;
}
```
遍历链表:
```
void traverse(List* list) {
Node* p = list->head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
```
销毁链表:
```
void destroyList(List* list) {
Node* p = list->head;
while (p != NULL) {
Node* q = p;
p = p->next;
free(q);
}
free(list);
}
```
以上是链表的简单实现,可以根据具体需求进行修改和扩展。
阅读全文