用c语言,已知顺序存储线性表的插入、删操作代码,请构造一个线性表:(1)实现其倒置操作,将结果输出显示;(2)删除其中的一个或多个元素,并将结果输出显示。 2、构建链式存储线性表,实现插入、打印、删除等功能。
时间: 2024-09-12 16:01:49 浏览: 42
在C语言中,为了实现顺序存储线性表的倒置操作和删除元素以及链式存储线性表的操作,我们需要分别使用数组和结构体来描述线性表。
**1. 顺序存储线性表**
```c
#include <stdio.h>
// 定义顺序表的节点
typedef struct {
int data;
struct Node* next;
} SeqNode;
// 插入操作
void insert(SeqNode** head, int value) {
SeqNode* newNode = (SeqNode*)malloc(sizeof(SeqNode));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
// 删除指定位置的元素(假设0开始计数)
void deleteElement(SeqNode** head, int index) {
if (*head == NULL) return;
if (index == 0) {
SeqNode* temp = *head;
*head = (*head)->next;
free(temp);
} else {
SeqNode* curr = *head;
for (int i = 1; i < index && curr != NULL; i++) {
curr = curr->next;
}
if (curr != NULL) {
SeqNode* temp = curr->next;
curr->next = curr->next->next;
free(temp);
}
}
}
// 打印线性表
void printList(SeqNode* head) {
SeqNode* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
// 倒置顺序表并输出
void reverseList(SeqNode** head) {
SeqNode* prev = NULL, *current = *head, *nextTemp;
while (current != NULL) {
nextTemp = current->next;
current->next = prev;
prev = current;
current = nextTemp;
}
*head = prev;
}
int main() {
SeqNode* seqHead = NULL;
// 插入元素
insert(&seqHead, 1);
insert(&seqHead, 2);
insert(&seqHead, 3);
// 输出原始列表
printf("Original list: ");
printList(seqHead);
// 倒置并输出
reverseList(&seqHead);
printf("Reversed list: ");
printList(seqHead);
// 删除第一个元素并输出
deleteElement(&seqHead, 0);
printf("After deleting first element: ");
printList(seqHead);
return 0;
}
```
**2. 链式存储线性表**
```c
#include <stdio.h>
struct ListNode {
int val;
struct ListNode* next;
};
// 插入操作
void insertToList(ListNode** head, int value) {
ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->val = value;
newNode->next = *head;
*head = newNode;
}
// 删除指定位置的元素
void deleteElement(ListNode** head, int index) {
if (*head == NULL) return;
if (index == 0) {
ListNode* temp = *head;
*head = (*head)->next;
free(temp);
} else {
ListNode* curr = *head;
for (int i = 1; i < index && curr != NULL; i++) {
curr = curr->next;
}
if (curr != NULL) {
ListNode* toDelete = curr->next;
curr->next = toDelete->next;
free(toDelete);
}
}
}
// 打印链表
void printList(ListNode* head) {
ListNode* temp = head;
while (temp != NULL) {
printf("%d ->", temp->val);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
ListNode* linkedListHead = NULL;
// 插入元素
insertToList(&linkedListHead, 1);
insertToList(&linkedListHead, 2);
insertToList(&linkedListHead, 3);
// 输出原始列表
printf("Original list: ");
printList(linkedListHead);
// 删除第一个元素并输出
deleteElement(&linkedListHead, 0);
printf("After deleting first element: ");
printList(linkedListHead);
return 0;
}
```
阅读全文