建立一个顺序表,包含数据1,2,3,4,5,6,7,8八个数据,输出顺序表元素个数,输出顺序表元素各值,输入要插入元素的位置和元素值,输出插入后的顺序表,输入要删除元素的位置,输出删除元素后的顺序表。c语言完整代码
时间: 2024-10-23 22:19:24 浏览: 24
在C语言中,我们可以创建一个简单的线性结构体来表示顺序表,并提供插入、删除和输出操作的功能。这里是一个简化的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义顺序表节点
typedef struct {
int data;
struct Node* next;
} Node;
// 初始化顺序表
Node* create_list(int arr[], int n) {
Node* head = (Node*)malloc(sizeof(Node));
head->data = arr[0];
head->next = NULL;
for (int i = 1; i < n; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = arr[i];
newNode->next = head->next;
head->next = newNode;
}
return head;
}
// 输出顺序表元素
void print_list(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
// 插入元素到指定位置
Node* insert_at_position(Node* head, int position, int value) {
if (position <= 0)
return head;
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = head;
Node* prev = head;
for (int i = 0; i < position - 1 && prev != NULL; i++)
prev = prev->next;
if (prev == NULL)
return newNode;
prev->next = newNode;
return head;
}
// 删除元素
Node* delete_at_position(Node* head, int position) {
if (head == NULL || position <= 0)
return head;
if (position == 1) {
Node* temp = head->next;
free(head);
head = temp;
return head;
}
Node* current = head;
for (int i = 1; i < position - 1 && current != NULL; i++)
current = current->next;
if (current == NULL)
return head;
Node* to_delete = current->next;
current->next = to_delete->next;
free(to_delete);
return head;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
int n = sizeof(arr) / sizeof(arr[0]);
Node* list = create_list(arr, n);
// 输出初始列表
printf("Initial List:\n");
print_list(list);
// 插入元素
int insertPos = 3, newValue = 9;
list = insert_at_position(list, insertPos, newValue);
printf("\nList after inserting at %d: \n", insertPos);
print_list(list);
// 删除元素
int deletePos = 5;
list = delete_at_position(list, deletePos);
printf("\nList after deleting at %d: \n", deletePos);
print_list(list);
return 0;
}
```
注意:这个代码示例仅适用于单向链表。如果你需要数组形式的顺序表,你可以直接存储数据并调整相应的插入和删除函数。
阅读全文