LeetCode 328. Odd Even Linked List

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.node

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.git

Example 1:github

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 ...ide

描述

給定一個單鏈表,把全部的奇數節點和偶數節點分別排在一塊兒。請注意,這裏的奇數節點和偶數節點指的是節點編號的奇偶性,而不是節點的值的奇偶性。ui

請嘗試使用原地算法完成。你的算法的空間複雜度應爲 O(1),時間複雜度應爲 O(nodes),nodes 爲節點總數。spa

示例 1:指針

輸入: 1->2->3->4->5->NULL
輸出: 1->3->5->2->4->NULL

示例 2:code

輸入: 2->1->3->5->6->4->7->NULL 
輸出: 2->3->6->7->1->5->4->NULL

說明:

應當保持奇數節點和偶數節點的相對順序。
鏈表的第一個節點視爲奇數節點,第二個節點視爲偶數節點,以此類推。

思路

  • 咱們聲明兩個鏈表,一個叫作「奇數鏈表」,另外一個叫作「偶數鏈表」,奇數鏈表只存儲奇數的節點,偶數鏈表只存儲偶數的節點。
  • 咱們依次從給定的節點中取出節點,依次添加到「奇數鏈表」和「偶數鏈表」中,最後咱們將「偶數鏈表」添加到「奇數鏈表」末尾。
# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-03-03 15:03:36
# @Last Modified by:   何睿
# @Last Modified time: 2019-03-03 15:59:29


# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution:
    def oddEvenList(self, head: ListNode) -> ListNode:
        # 少於兩個節點的狀況直接返回
        if not head or not head.next: return head
        # 記錄下頭節點
        oddhead, evenhead = head, head.next
        # 記錄下尾節點,初始是頭節點和尾節點是重合的
        oddtail, eventail = head, head.next
        node = head.next.next
        oddtail.next, eventail.next = None, None
        isodd = True
        while node:
            # 把當前節點掛到奇數鏈表後面
            if isodd:
                # 掛載當前節點
                oddtail.next = node
                # 剩餘節點指針向後移動一個
                node = node.next
                # 尾節點向後移動一個
                oddtail = oddtail.next
                # 將尾節點的下一個節點置爲空
                oddtail.next = None
                # 下一次將掛載到奇數節點後面
                isodd = False
            # 把當前節點掛到偶數節點後面
            else:
                # 掛載當前節點
                eventail.next = node
                # 剩餘節點向後移動一個
                node = node.next
                # 尾節點向後移動一個
                eventail = eventail.next
                # 將尾節點的下一個節點置爲空
                eventail.next = None
                # 下一次將掛載到偶數節點後面
                isodd = True
        # 偶數鏈將掛載到奇數鏈表後面
        oddtail.next = evenhead
        # 返回奇數鏈表的頭節點
        return oddhead

源代碼文件在 這裏
©本文首發於 何睿的博客 ,歡迎轉載,轉載需保留 文章來源 ,做者信息和本聲明.微信公衆號:techruicore

相關文章
相關標籤/搜索