Leetcode|Leetcode 328. Odd Even Linked List
【Leetcode|Leetcode 328. Odd Even Linked List】文章作者:Tyan
博客:noahsnail.com|CSDN|
1. Description
文章图片
Odd Even Linked List 2. Solution
- Version 1
/**
* 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) {
return head;
}
ListNode* even = head->next;
ListNode* current = head;
ListNode* next = nullptr;
while(current->next) {
next = current->next;
current->next = current->next->next;
current = next;
}
current = head;
while(current->next) {
current = current->next;
}
current->next = even;
return head;
}
};
- Version 2
/**
* 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) {
return head;
}
int count = 1;
ListNode* odd = head;
ListNode* even = head->next;
ListNode* current = head;
ListNode* next = nullptr;
while(current->next) {
next = current->next;
current->next = current->next->next;
current = next;
count++;
if(count % 2) {
odd = current;
}
}
current = head;
odd->next = even;
return head;
}
};
- Version 3
/**
* 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) {
return head;
}
ListNode* odd = head;
ListNode* even = head->next;
ListNode* even_head = head->next;
while(odd->next && even->next) {
odd->next = odd->next->next;
even->next = even->next->next;
odd = odd->next;
even = even->next;
}
odd->next = even_head;
return head;
}
};
Reference
- https://leetcode.com/problems/odd-even-linked-list/description/
推荐阅读
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- leetcode|leetcode 92. 反转链表 II
- 二叉树路径节点关键值和等于目标值(LeetCode--112&LeetCode--113)
- LeetCode算法题-11.|LeetCode算法题-11. 盛最多水的容器(Swift)
- LeetCode(03)Longest|LeetCode(03)Longest Substring Without Repeating Characters
- Leetcode|Leetcode No.198打家劫舍
- [leetcode数组系列]1两数之和
- 数据结构和算法|LeetCode 的正确使用方式
- leetcode|今天开始记录自己的力扣之路
- [Toddler's|[Toddler's Bottle]-random