写一个全功能的单向链表
时间: 2023-03-27 08:01:42 浏览: 71
好的,我可以回答这个问题。单向链表是一种常见的数据结构,它由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的指针。以下是一个简单的单向链表的实现:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct LinkedList {
Node* head;
int size;
} LinkedList;
LinkedList* createLinkedList() {
LinkedList* list = (LinkedList*)malloc(sizeof(LinkedList));
list->head = NULL;
list->size = ;
return list;
}
void addNode(LinkedList* list, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (list->head == NULL) {
list->head = newNode;
} else {
Node* current = list->head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
list->size++;
}
void removeNode(LinkedList* list, int data) {
if (list->head == NULL) {
return;
}
if (list->head->data == data) {
Node* temp = list->head;
list->head = list->head->next;
free(temp);
list->size--;
return;
}
Node* current = list->head;
while (current->next != NULL) {
if (current->next->data == data) {
Node* temp = current->next;
current->next = current->next->next;
free(temp);
list->size--;
return;
}
current = current->next;
}
}
void printList(LinkedList* list) {
Node* current = list->head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
LinkedList* list = createLinkedList();
addNode(list, 1);
addNode(list, 2);
addNode(list, 3);
printList(list);
removeNode(list, 2);
printList(list);
return ;
}
```
这个程序实现了一个简单的单向链表,包括创建链表、添加节点、删除节点和打印链表等功能。当然,这只是一个基础的实现,你可以根据自己的需求进行扩展和优化。