#include <stdio.h>
#include <stdlib.h>
// 链表节点定义
struct Node {
int data;
struct Node* next;
};
// 插入节点到链表尾部
void insertNode(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {//空指针
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 分解链表
void splitLinkedList(struct Node* head, struct Node** oddHead, struct Node** evenHead) {
struct Node* current = head;
while (current != NULL) {
if (current->data % 2 == 0) {
insertNode(evenHead, current->data);
} else {
insertNode(oddHead, current->data);
}
current = current->next;
}
}
// 打印链表
void printLinkedList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
struct Node* oddHead = NULL;
struct Node* evenHead = NULL;
int data;
while (1) {
scanf("%d", &data);
if (data == -1) {
break;
}
insertNode(&head, data);//如果定义的是指针head,双指针定义的函数需要传进去地址
}
splitLinkedList(head, &oddHead, &evenHead);
printLinkedList(head);
printLinkedList(oddHead);
printLinkedList(evenHead);
// 释放内存
while (head != NULL) {
struct Node* temp = head;
head = head->next;
free(temp);
}
while (oddHead != NULL) {
struct Node* temp = oddHead;
oddHead = oddHead->next;
free(temp);
}
while (evenHead != NULL) {
struct Node* temp = evenHead;
evenHead = evenHead->next;
free(temp);
}
return 0;
}
经典pta输入式链表用例
最新推荐文章于 2024-07-25 17:43:13 发布