(1) 设数据元素为整数,实现这样的线性表的链式存储表示。用c++语言完成
时间: 2024-05-06 08:20:31 浏览: 8
定义数据结构:
```c
typedef struct node{
int data; // 数据域
struct node* next; // 指针域
}Node;
typedef struct list{
Node* head; // 头节点指针
}List;
```
实现创建链表、插入结点、删除结点、查找结点等基本操作:
```c
#include <stdlib.h>
// 创建链表
List* createList(){
List* list = (List*)malloc(sizeof(List)); // 申请链表内存
list->head = NULL; // 初始化头节点指针
return list;
}
// 插入结点
void insertNode(List* list, int data){
Node* node = (Node*)malloc(sizeof(Node)); // 申请结点内存
node->data = data; // 初始化结点数据
node->next = list->head; // 将新结点指向原头节点
list->head = node; // 更新头节点指针
}
// 删除结点
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){ // 找到结点
if(q == NULL){ // 要删除的结点是头节点
list->head = p->next; // 更新头节点指针
}else{
q->next = p->next; // 将前一个结点指向要删除结点的下一个结点
}
free(p); // 释放要删除结点的内存
}
}
// 查找结点
Node* searchNode(List* list, int data){
Node* p = list->head; // 从头节点开始遍历
while(p != NULL && p->data != data){ // 遍历链表,找到要查找的结点
p = p->next;
}
return p; // 返回找到的结点指针
}
// 输出链表
void printList(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->next;
free(p);
p = q;
}
free(list); // 释放链表内存
}
```
示例代码:
```c
#include <stdio.h>
int main(){
List* list = createList(); // 创建链表
insertNode(list, 1); // 插入结点
insertNode(list, 2);
insertNode(list, 3);
insertNode(list, 4);
printList(list); // 输出链表
deleteNode(list, 3); // 删除结点
printList(list); // 输出链表
Node* node = searchNode(list, 2); // 查找结点
if(node != NULL){
printf("%d\n", node->data); // 输出结点数据
}
destroyList(list); // 销毁链表
return 0;
}
```