用C语言编程实现一个对单链表进行基本操作的系统,主要包括表的创建,输入,查询,取值,插入,删除,输出等操作(可以采用带头结点和不带头结点的单链表)
时间: 2024-04-29 14:24:18 浏览: 25
以下是使用带头结点的单链表实现以上操作的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int val;
struct Node *next;
};
struct Node* createList() {
struct Node *head = (struct Node*)malloc(sizeof(struct Node));
head->next = NULL;
return head;
}
void insertNode(struct Node *head, int val) {
struct Node *node = (struct Node*)malloc(sizeof(struct Node));
node->val = val;
node->next = head->next;
head->next = node;
}
void deleteNode(struct Node *head, int val) {
struct Node *prev = head;
struct Node *curr = head->next;
while (curr != NULL) {
if (curr->val == val) {
prev->next = curr->next;
free(curr);
return;
}
prev = curr;
curr = curr->next;
}
}
void printList(struct Node *head) {
struct Node *curr = head->next;
while (curr != NULL) {
printf("%d ", curr->val);
curr = curr->next;
}
printf("\n");
}
int searchNode(struct Node *head, int val) {
struct Node *curr = head->next;
while (curr != NULL) {
if (curr->val == val) {
return 1;
}
curr = curr->next;
}
return 0;
}
int getNode(struct Node *head, int index) {
struct Node *curr = head->next;
int i = 0;
while (curr != NULL && i < index) {
curr = curr->next;
i++;
}
if (curr == NULL) {
return -1;
}
return curr->val;
}
int main() {
struct Node *head = createList();
int n, val, index;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &val);
insertNode(head, val);
}
printf("List: ");
printList(head);
printf("Enter value to search: ");
scanf("%d", &val);
if (searchNode(head, val)) {
printf("%d found in the list\n", val);
} else {
printf("%d not found in the list\n", val);
}
printf("Enter index to get value: ");
scanf("%d", &index);
int res = getNode(head, index);
if (res == -1) {
printf("Invalid index\n");
} else {
printf("Value at index %d is %d\n", index, res);
}
printf("Enter value to insert: ");
scanf("%d", &val);
insertNode(head, val);
printf("List after insertion: ");
printList(head);
printf("Enter value to delete: ");
scanf("%d", &val);
deleteNode(head, val);
printf("List after deletion: ");
printList(head);
return 0;
}
```
在该程序中,使用`createList`函数创建一个带头结点的单链表,并返回头结点指针。使用`insertNode`函数在链表中插入一个值为`val`的节点。使用`deleteNode`函数删除链表中值为`val`的节点。使用`printList`函数输出链表中的所有元素。使用`searchNode`函数查找链表中是否存在值为`val`的节点。使用`getNode`函数获取链表中指定索引`index`处的节点的值。在`main`函数中,先读入元素数量和元素值,然后插入到链表中。接着,分别进行查询、取值、插入、删除等操作,并输出链表的最终状态。