C++ algorithm learning (Like: 328. Parity linked list)

Given a singly linked list, arrange all odd and even nodes together. Please note that the odd and even nodes here refer to the parity of the node number, not the parity of the node's value.

Please try to use the in-place algorithm to complete. The space complexity of your algorithm should be O(1), the time complexity should be O(nodes), and nodes should be the total number of nodes.

Example 1:

Input: 1->2->3->4->5->NULL Output: 1->3->5->2->4->NULL

Example 2:

Input: 2->1->3->5->6->4->7->NULL Output: 2->3->6->7->1->5->4->NULL

Description:

The relative order of odd and even nodes should be maintained. The first node of the linked list is regarded as an odd node, the second node is regarded as an even node, and so on.

Source: LeetCode
Link: https://leetcode-cn.com/problems/odd-even-linked-list The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Personal understanding, when I got the question, I first considered dividing it into two linked lists, and finally combined the two linked lists ==, so I wrote directly:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* oddEvenList(ListNode* head) {
    
    
        if(head == nullptr)
        {
    
    
            return head;
        }
        ListNode* head1 = new ListNode();
        ListNode* n1 = head1;
        n1->val = head->val;
        head=head->next;
        if(head == nullptr)
        {
    
    
            return head1;
        }
        ListNode* head2 = new ListNode();
        ListNode* n2 = head2;
        n2->val = head->val;
        head=head->next;
        int i = 3;
        while(head!=nullptr){
    
    
        ListNode* Node = new ListNode();
        Node->val = head->val;
        Node->next =NULL;
        if(i%2 == 1){
    
    
        n1->next = Node;
        n1 = n1->next;
        }
        if(i%2 == 0){
    
    
        n2->next = Node;
        n2 = n2->next;
        }
        head = head->next;
        i++;
        }
        n1->next = head2;
        return head1;
    }
};

Passed, I personally didn't learn the linked list very well, and I wrote it entirely by feeling.

Guess you like

Origin blog.csdn.net/weixin_45743162/article/details/109676155