C++数据结构代码实现
时间: 2023-11-14 09:58:58 浏览: 41
C语言中,实现数据结构常用的方式是使用结构体和指针。单链表是一种常见的数据结构,在C语言中可以通过结构体定义来实现。下面是一种常见的单链表的定义和实现方式:
```c
// 单链表节点定义
struct ListNode {
int data; // 数据域
struct ListNode* next; // 指针域:指向下一个节点的指针
};
// 单链表的创建
struct ListNode* createLinkedList(int arr[], int n) {
struct ListNode* head = NULL;
struct ListNode* tail = NULL;
for (int i = 0; i < n; i++) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->data = arr[i];
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// 单链表的打印
void printLinkedList(struct ListNode* head) {
struct ListNode* p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
// 单链表的销毁
void destroyLinkedList(struct ListNode* head) {
struct ListNode* p = head;
while (p != NULL) {
struct ListNode* temp = p;
p = p->next;
free(temp);
}
}
// 单链表的插入
void insertNode(struct ListNode** head, int data, int position) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->data = data;
newNode->next = NULL;
if (position == 0) {
newNode->next = *head;
*head = newNode;
} else {
struct ListNode* p = *head;
int count = 0;
while (count < position - 1 && p != NULL) {
p = p->next;
count++;
}
if (p != NULL) {
newNode->next = p->next;
p->next = newNode;
}
}
}
// 单链表的删除
void deleteNode(struct ListNode** head, int position) {
if (*head == NULL) {
return;
}
struct ListNode* p = *head;
if (position == 0) {
*head = (*head)->next;
free(p);
} else {
int count = 0;
while (count < position - 1 && p != NULL) {
p = p->next;
count++;
}
if (p != NULL && p->next != NULL) {
struct ListNode* temp = p->next;
p->next = p->next->next;
free(temp);
}
}
}
```