#include <stdio.h> #include <stdlib.h>

typedef struct Node { int data; struct Node* next; } Node;

typedef struct LinkedList { Node* head; } LinkedList;

LinkedList* createLinkedList() { LinkedList* list = (LinkedList*)malloc(sizeof(LinkedList)); list->head = NULL; return list; }

void insert(LinkedList* list, int data) { Node* new_node = (Node*)malloc(sizeof(Node)); new_node->data = data; new_node->next = NULL;

if (list->head == NULL || data < list->head->data) {
    new_node->next = list->head;
    list->head = new_node;
} else {
    Node* current = list->head;
    while (current->next != NULL && data > current->next->data) {
        current = current->next;
    }
    new_node->next = current->next;
    current->next = new_node;
}

}

void traverse(LinkedList* list) { Node* current = list->head; while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); }

int search(LinkedList* list, int target) { Node* current = list->head; while (current != NULL) { if (current->data == target) { return 1; } current = current->next; } return 0; }

LinkedList* buildLinkedList() { LinkedList* list = createLinkedList(); int* sequence; int size; while (1) { printf("请输入递增的整型元素序列,以空格分隔: "); char input[100]; fgets(input, sizeof(input), stdin); sscanf(input, "%d", &size); if (size <= 0) { printf("输入错误,请重新输入递增的整型元素序列! "); continue; } sequence = (int*)malloc(size * sizeof(int)); int num; int i = 0; int valid = 1; char* token = strtok(input, " "); while (token != NULL) { sscanf(token, "%d", &num); if (i > 0 && num <= sequence[i-1]) { valid = 0; break; } sequence[i++] = num; token = strtok(NULL, " "); } if (valid) { break; } else { printf("输入错误,请重新输入递增的整型元素序列! "); } }

for (int i = 0; i < size; i++) {
    insert(list, sequence[i]);
}

free(sequence);
return list;

}

int main() { LinkedList* list = buildLinkedList(); printf("链表遍历结果: "); traverse(list);

int target;
printf("请输入要查找的元素: ");
scanf("%d", &target);
if (search(list, target)) {
    printf("元素 %d 在链表中找到了。

", target); } else { printf("元素 %d 不在链表中。 ", target); }

int new_num;
printf("请输入要插入的元素: ");
scanf("%d", &new_num);
insert(list, new_num);
printf("插入元素后的链表遍历结果:

"); traverse(list);

return 0;

}

C语言链表操作练习题:建立、遍历、查找和插入

原文地址: http://www.cveoy.top/t/topic/bLBD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录