0%

leetcode Odd Even Linked List

leetcode 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: Given 1->2->3->4->5->NULL, return 1->3->5->2->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 ...

题目地址:leetcode Odd Even Linked List

题意:给定一个单向链表,要求你将所有奇数位置的节点“提”到前面,如

  • 1->2->3->4->5->NULL

变为

  • 1->3->5->2->4->NULL

思路:

很简单的,用两个指针即可,一个指针p指向当前遍历的奇数节点的最后一个位置,另一个指针q指向待提取的奇数节点的前一个位置。

然后把q.next 的节点删除,插入到p.next的位置即可

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (!head) return head;
ListNode *p = head, *q = head;
while (q) {
q = q->next;
if (!q || !q->next) break;
ListNode *next_p = p->next, *next_q = q->next;
q->next = next_q->next;
p->next = next_q;
next_q->next = next_p;
p = p->next;
}
return head;
}
};

 

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public ListNode oddEvenList(ListNode head) {
if (head == null) return head;
ListNode p = head, q =head;
while (q != null) {
q = q.next;
if (q==null q.next==null) break;
ListNode next_p = p.next, next_q = q.next;
q.next = next_q.next;
p.next = next_q;
next_q.next = next_p;
p = p.next;
}
return head;
}
}

 

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head: return head
p, q = head, head
while q:
q = q.next
if not q or not q.next: break
next_p, next_q = p.next, q.next
q.next = next_q.next
p.next ,next_q.next = next_q , next_p
p = p.next
return head

 

本文是leetcode 328 Odd Even Linked List 的题解,更多题解可见 https://www.hrwhisper.me/leetcode-algorithm-solution/

请我喝杯咖啡吧~