c语言代码:新建一个顺序表,将输入的数据存入顺序表,并将输入的元素输出,并完成以下操作,1、删除指定位置的元素;2、向指定位置插入元素;3、查找某元素在线性表中的位置;
时间: 2024-10-13 20:07:52 浏览: 25
栈:顺序栈和链表栈_C语言项目
在C语言中,我们可以使用结构体和指针来创建一个简单的顺序表。下面是一个基本的实现,包括初始化、添加元素、删除元素和查找元素的功能:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义顺序表节点结构
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建并初始化顺序表
Node* createList() {
Node* head = (Node*)malloc(sizeof(Node));
if (!head) {
printf("Memory allocation failed.\n");
return NULL;
}
head->data = -1; // 空表标记
head->next = NULL;
return head;
}
// 添加元素到列表
void insertElement(Node** head, int value, int position) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
if (position == 0) { // 插入在首位
*head = newNode;
} else {
Node* current = *head;
for (int i = 1; i < position && current != NULL; i++) {
current = current->next;
}
if (current != NULL) {
newNode->next = current->next;
current->next = newNode;
} else {
printf("Position out of range.\n");
}
}
}
// 删除指定位置的元素
void deleteElement(Node** head, int position) {
if (*head == NULL) {
printf("List is empty.\n");
return;
}
Node* current = *head;
Node* previous = NULL;
if (position == 0) { // 删除首位
*head = current->next;
} else {
for (int i = 1; i < position && current != NULL; i++) {
previous = current;
current = current->next;
}
if (current != NULL) {
previous->next = current->next;
} else {
printf("Position out of range.\n");
}
}
}
// 查找元素的位置
int findElement(Node* head, int value) {
Node* current = head;
int position = 0;
while (current != NULL) {
if (current->data == value)
return position;
current = current->next;
position++;
}
return -1; // 元素未找到
}
// 打印列表
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
Node* listHead = createList();
// 用户输入数据并操作
int input, choice;
do {
printf("Choose an operation:\n");
printf("1. Insert at position\n");
printf("2. Delete element by position\n");
printf("3. Find element\n");
printf("4. Print list\n");
printf("5. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value and position: ");
scanf("%d %d", &input, &position);
insertElement(&listHead, input, position);
break;
case 2:
printf("Enter position to delete: ");
scanf("%d", &position);
deleteElement(&listHead, position);
break;
case 3:
printf("Enter value to search: ");
scanf("%d", &input);
int pos = findElement(listHead, input);
if (pos != -1)
printf("Element found at position %d.\n", pos);
else
printf("Element not found.\n");
break;
case 4:
printList(listHead);
break;
case 5:
break;
default:
printf("Invalid choice.\n");
}
} while (choice != 5);
return 0;
}
```
阅读全文