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

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

typedef struct LinkedList { Node* head; Node* tail; } LinkedList;

LinkedList* createLinkedList() { LinkedList* list = (LinkedList*)malloc(sizeof(LinkedList)); list->head = NULL; list->tail = 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) {
    list->head = new_node;
    list->tail = new_node;
} else {
    list->tail->next = new_node;
    list->tail = new_node;
}

}

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

void doubleSize(LinkedList* list) { Node* current = list->head; while (current != NULL) { Node* new_node = (Node*)malloc(sizeof(Node)); new_node->data = current->data; new_node->next = current->next; current->next = new_node; current = new_node->next; } list->tail = list->tail->next; }

bool isPrime(int num) { if (num < 2) { return false; } for (int i = 2; i <= num / 2; i++) { if (num % i == 0) { return false; } } return true; }

void splitByPrime(LinkedList* list, LinkedList* primeList, LinkedList* nonPrimeList) { Node* current = list->head; while (current != NULL) { if (isPrime(current->data)) { insert(primeList, current->data); } else { insert(nonPrimeList, current->data); } Node* temp = current; current = current->next; free(temp); } free(list); }

int main() { LinkedList* list = createLinkedList(); LinkedList* primeList = createLinkedList(); LinkedList* nonPrimeList = createLinkedList();

int size;
printf("请输入链表的大小: ");
scanf("%d", &size);

printf("请输入链表的元素,以空格分隔: ");
for (int i = 0; i < size; i++) {
    int data;
    scanf("%d", &data);
    insert(list, data);
}

printf("链表的初始状态:

"); traverse(list);

doubleSize(list);
printf("链表扩大两倍后的状态:

"); traverse(list);

splitByPrime(list, primeList, nonPrimeList);
printf("按照是否是素数拆分后的链表:

"); printf("素数链表:"); traverse(primeList); printf("非素数链表:"); traverse(nonPrimeList);

return 0;

}


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

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