用C语言编程实现顺序表的输入、输出、插入、删除操作
时间: 2024-09-26 12:04:26 浏览: 66
在C语言中,我们可以使用结构体和函数来实现顺序表的数据结构,包括输入(读取)、输出(显示)、插入和删除操作。以下是简单的例子:
首先,定义一个顺序表节点的结构体:
```c
typedef struct Node {
int data;
struct Node* next;
} ListNode;
```
然后,创建用于输入、输出、插入和删除的函数:
1. **输入(插入首元素)**:
```c
void insertAtBegin(ListNode** head, int value) {
ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
```
2. **输出(遍历并打印)**:
```c
void printList(ListNode* head) {
ListNode* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
```
3. **插入(在指定位置插入)**:
```c
void insertAtPosition(ListNode** head, int position, int value) {
ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->data = value;
if (position == 0) {
newNode->next = *head;
*head = newNode;
} else {
ListNode* temp = *head;
for (int i = 0; i < position - 1 && temp != NULL; i++) {
temp = temp->next;
}
if (temp != NULL) {
newNode->next = temp->next;
temp->next = newNode;
}
}
}
```
4. **删除(删除指定位置的元素)**:
```c
void deleteAtPosition(ListNode** head, int position) {
if (*head == NULL || position <= 0) return;
ListNode* temp = *head;
if (position == 1) {
*head = temp->next;
free(temp);
return;
}
for (int i = 1; temp != NULL && i < position - 1; i++) {
temp = temp->next;
}
if (temp != NULL && temp->next != NULL) {
ListNode* toDelete = temp->next;
temp->next = temp->next->next;
free(toDelete);
}
}
```
阅读全文