题目:
328. Odd Even Linked List(medium)
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.1
2
3
4
5
6Example 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 …
题目大意:
将单链表中位置重新调整,其中的奇数位置排在一起、偶数位置排在一起,奇数位置在前。
时间复杂度O(n),空间复杂度O(1)
注:保证奇数结点和偶数结点的相对顺序不变
解题思路:
利用两个新指针:odd和even,分别记住两个链表分别的连接关系;还需要记住odd链表接下来要连接的第一个偶数结点:evenHead,为原先链表的第一个偶数位置结点。
代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17Java:
public ListNode oddEvenList(ListNode head){
if(head == null || head.next == null) return head;
ListNode odd = head, even = head.next, evenHead = even;
while(odd.next != null && even.next != null){
odd.next = odd.next.next;
odd = odd.next;
even.next = even.next.next;
even = even.next;
}
odd.next = evenHead;
return head;
}
Python: