leetcode笔记--Odd Even Linked List

来源:互联网 发布:家庭ktv 知乎 编辑:程序博客网 时间:2024/05/16 04:58

题目:难度(Easy)

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 ...
Tags:Linked List

分析:将偶数位置的节点放在奇数位置节点的后面。相当于将链表分成2部分,奇数链表与偶数链表,他们的尾指针分别为oddTail与evenTail,依次遍历原链表,当前的节点设为oddCur,那么需要将oddCur加入到奇数链表中,oddCur->next加入到偶数链表中,并修改两个链表的尾指针为新加入的节点位置,然后将奇数链表的尾指针与偶数链表的头指针相链接,然后循环下去,直至所有节点满足要求。

演示:按算法描述,在进行循环之前的初始状态如下图:


循环第一次后,链表的状态如下:


循环第二次后,链表的状态如下:


循环第三次后,链表的状态如下:


循环第四次后,链表的状态如下:


至此,循环结束。

代码实现:

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def oddEvenList(self, head):        """        :type head: ListNode        :rtype: ListNode        """        if head is None:            return None        oddTail = head        evenHead = head.next        evenTail = head.next                while evenTail is not None and evenTail.next is not None:            oddCur = evenTail.next            #为奇数链表增加一个节点            oddTail.next = oddCur            #为偶数链表增加一个节点            evenTail.next = oddCur.next            #将奇数链表的尾指针与偶数链表的头指针相链接            oddCur.next = evenHead            #奇数链表与偶数链表的尾指针均向后移动            oddTail = oddTail.next            evenTail = evenTail.next                    return head


0 0