题目描述
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 1:
Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/odd-even-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码
i从0开始递增,利用“i%2==0”来判断奇偶。
#include <iostream>
using namespace std;
/// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/// Split the Linked List into two and then merge
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(head == NULL || head->next == NULL || head->next->next == NULL)
return head;
ListNode* dummyHead1 = new ListNode(-1);
ListNode* dummyHead2 = new ListNode(-1);
ListNode* p1 = dummyHead1;
ListNode* p2 = dummyHead2;
ListNode* p = head;
for(int i = 0; p; i ++)
if(i % 2 == 0){
p1->next = p;
p = p->next;
p1 = p1->next;
p1->next = NULL;
}
else{
p2->next = p;
p = p->next;
p2 = p2->next;
p2->next = NULL;
}
p1->next = dummyHead2->next;
ListNode* ret = dummyHead1->next;
delete dummyHead1;
delete dummyHead2;
return ret;
}
};
int main() {
return 0;
}
思路二
无需额外判定奇偶,利用自然逻辑,即第一个结点为奇,第二个就为偶。
#include <iostream>
using namespace std;
/// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/// Split the Linked List into two and then merge
/// Keep one in original Linked List
///
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(head == NULL || head->next == NULL || head->next->next == NULL)
return head;
ListNode* dummyHead2 = new ListNode(-1);
ListNode* p2 = dummyHead2;
ListNode* p = head;
while(p->next){
p2->next = p->next;
if(p->next->next == NULL){
p->next = NULL;
break;
}
p->next = p->next->next;
p = p->next;
p2 = p2->next;
p2->next = NULL;
}
p->next = dummyHead2->next;
delete dummyHead2;
return head;
}
};
int main() {
return 0;
}