Day16-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.
从一个链表中将奇数位置的节点,移到偶数位置的节点前面(注意这里说的奇偶是节点位置的所以即从第一个位置为奇数位置,第二个位置为偶数位置依次递推,而不是节点里面值的奇偶)。要求空间复杂度为O(1),时间复杂度为节点的O(nodes).
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
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(1),因为其实并没有建立额外的节点,只是用了三个指针链接了节点。听他们这么一说似乎是这样的。。。。。
看了官方的solution的解法图,似乎也是这样解的。
# 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 head is None:
return head
odd = oddHead = head
even = evenHead = head.next
while even and even.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = evenHead
return oddHead