题目:
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.
这道题我是先把偶数节点保存下来,然后再插入到原链表的末尾就行了
(faster 73.59%)
/**
* 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:
int getLength(ListNode* head){
int count = 0;
while(head != NULL)
{
count++;
head = head->next;
}
return count;
}
ListNode* oddEvenList(ListNode* head) {
auto cnt = getLength(head);
ListNode* head1 = new ListNode;
ListNode* p = head1;
ListNode*r, *s;
r = head;
int i = 1;
while(i < cnt){
if(i % 2 != 0){
s = r->next;
p->next = s;
p = s;
r->next = r->next->next;
i++;
}
i++;
r = r ->next;
}
p->next = nullptr;
r = head;
if(r == nullptr)return head;
while(r->next != NULL){
r = r->next;
}
r->next = head1->next;
return head;
}
};
博客围绕LeetCode上的一道链表题目展开,题目要求将单链表的奇数节点和偶数节点分组,且要原地操作,满足O(1)空间复杂度和O(nodes)时间复杂度。博主采用先保存偶数节点,再插入原链表末尾的方法解决,速度超过73.59%。

205

被折叠的 条评论
为什么被折叠?



