leetcode 328 Odd Even Linked List(调整链表使得奇数位置的元素位于偶数位置元素之前)


Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
    You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example:
    Given 1->2->3->4->5->NULL,
    return 1->3->5->2->4->NULL.

题目的大概意思是:把链表中奇数位置的元素放在偶数位置的元素之前。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(!head||!head->next||!head->next->next) return head;
        ListNode *p1=head;
        ListNode *p2head=head->next;
        ListNode *p2=p2head;
        while(p1->next&&p1->next->next)
        {
            p1->next=p2->next;
            p2->next=p2->next->next;
            p1=p1->next;
            p2=p2->next;
        }
        p1->next=p2head;
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/momo_mo520/article/details/80377993