328 Odd Even Linked List 奇偶鏈表
Description:
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:
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
Constraints:
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 ...
The length of the linked list is between [0, 10^4].
題目描述:
給定一個單鏈表浙于,把所有的奇數節(jié)點和偶數節(jié)點分別排在一起。請注意秦踪,這里的奇數節(jié)點和偶數節(jié)點指的是節(jié)點編號的奇偶性拖刃,而不是節(jié)點的值的奇偶性跟伏。
請嘗試使用原地算法完成耻姥。你的算法的空間復雜度應為 O(1),時間復雜度應為 O(nodes)厕吉,nodes 為節(jié)點總數酱固。
示例 :
示例 1:
輸入: 1->2->3->4->5->NULL
輸出: 1->3->5->2->4->NULL
示例 2:
輸入: 2->1->3->5->6->4->7->NULL
輸出: 2->3->6->7->1->5->4->NULL
說明:
應當保持奇數節(jié)點和偶數節(jié)點的相對順序。
鏈表的第一個節(jié)點視為奇數節(jié)點头朱,第二個節(jié)點視為偶數節(jié)點运悲,以此類推。
思路:
雙指針分別指向奇數節(jié)點和偶數節(jié)點
分別遍歷賦值
最后將奇數和偶數鏈表連接起來
時間復雜度O(n), 空間復雜度O(1)
代碼:
C++:
/**
* 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:
ListNode* oddEvenList(ListNode* head)
{
if (!head) return head;
ListNode *p = head, *q = head -> next, *r = head -> next;
while (q and q -> next)
{
p -> next = p -> next -> next;
q -> next = q -> next -> next;
p = p -> next;
q = q -> next;
}
p -> next = r;
return head;
}
};
Java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode oddEvenList(ListNode head) {
if (head == null) return head;
ListNode p = head, q = head.next, r = head.next;
while (q != null && q.next != null) {
p.next = p.next.next;
q.next = q.next.next;
p = p.next;
q = q.next;
}
p.next = r;
return head;
}
}
Python:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head:
return head
p, q, r = head, head.next, head.next
while q and q.next:
p.next, q.next, p, q = p.next.next, q.next.next, p.next.next, q.next.next
p.next = r
return head