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 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
Note:
- The relative order inside both the even and odd groups should remain as it was in the input.
- The first node is considered odd, the second node even and so on ...
题目链接:https://leetcode.com/problems/odd-even-linked-list/
解法
此题和list partition那道题很像,但使用法一直接插入过于复杂,适合使用法二拆成两个链来做。
这里可以不实用假头,因为没有需要向链头插入的需求。
/**
* 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==NULL || head->next==NULL) return head;
ListNode *odd = head;
ListNode *even = head->next;
head = even->next;
ListNode *odd_cur = odd, *even_cur = even;
while(head!=NULL){
odd_cur->next = head;
odd_cur = head;
head = head->next;
if(head!=NULL){
even_cur->next = head;
even_cur = head;
head = head->next;
}
}
odd_cur->next = even;
even_cur->next = NULL;
return odd;
}
};

本文介绍了一种在链表中按奇偶节点重新排列的方法,确保所有奇数节点位于所有偶数节点之前,同时保持各自组内原始顺序不变。算法在O(1)空间复杂度和O(n)时间复杂度下运行,适用于LeetCode 328号问题“奇偶链表”。通过将链表拆分为奇数和偶数两部分,然后重新连接,实现了高效且简洁的解决方案。

252

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



