题解 | #链表的奇偶重排#
链表的奇偶重排
http://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
class Solution:
def oddEvenList(self , head: ListNode) -> ListNode:
# write code here
if head is None:
return head
one_head = ListNode(-1)
two_head = ListNode(-1)
one_head = head
two_head = head.next
two_ptr = two_head
one_ptr = one_head
while one_ptr.next and one_ptr.next.next:
one_ptr.next = one_ptr.next.next
two_ptr.next = two_ptr.next.next
one_ptr = one_ptr.next
two_ptr = two_ptr.next
one_ptr.next = two_head
return one_head
先使用两个节点保存奇数的头节点和偶数的头节点。再进行指针移动。设置两个指针,一个只想头节点,一个指向第二个节点,如果某个节点的下一个或下下为空,则停止,先移动后面的节点,如果先移动前面的节点,则无法找到正确的节点。终止后,让奇数的指针指向偶数的头节点