将链表分割成奇数链表和偶数链表

基础思路

创建另外两个链表进行操作
#include 
#include 

// 链表节点定义
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;
}

第二种思路

直接在原本的基础上进行操作(这里删除函数挺重要的)
void deleteNodeWithData(Node **head, Node* nodeToDelete) {
    if (nodeToDelete == NULL || *head == NULL) {
        return;
    }

    if (*head == nodeToDelete) {
        *head = nodeToDelete->next;
    } else {
        Node* current = *head;
        while (current != NULL && current->next != nodeToDelete) {
            current = current->next;
        }
        if (current != NULL) {
            current->next = nodeToDelete->next;
        }
    }

    free(nodeToDelete);
}

void high_level_5(Node **DLList1, Node *B)
{
    Node *p;
    Node *prev;
    p = (*DLList1)->next;
    // prev = *DLList1;

    while (p)
    {
        if ((p->data) % 2 != 0)
        {
            p = p->next;
        }
        else
        {
            prev = p;
			p = p->next;
			addToAnotherList(prev, B);
            // prev->next = p->next; // 删除当前节点
            
			
			deleteNodeWithData(DLList1,prev);
			
            
        }
    }
}

你可能感兴趣的:(链表,数据结构)