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.
Link: https://leetcode.com/problems/odd-even-linked-list/
Examples:
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
思路: 把第奇数个节点放在一起,第偶数个节点放在一起,然后连成一个整体。所以我们遍历一遍,把每个节点分别连接到奇数链表和偶数链表上,然后再将奇数链表的尾和偶数链表的头连接,返回奇数链表的头就可以了。
class Solution(object): def oddEvenList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return head if not head.next: return head p = head odd = ListNode(0) oddhead = odd even = ListNode(0) evenhead = even i = 1 while p: if i % 2 == 1: odd.next = p odd = odd.next else: even.next = p even = even.next p = p.next i += 1 odd.next = evenhead.next even.next = None return oddhead.next
日期: 2020-12-03 平平常常的日子真是好幸福