zoukankan      html  css  js  c++  java
  • leetcode 328 Odd Even Linked List

    题目链接:https://leetcode.com/problems/odd-even-linked-list/

    思路分析:题目为链表操作题,比较容易。需要特别注意的是对于特殊情况的处理,如当链表为空或者链表的长度为1时,不存在第偶数个结点组成的链表。

    代码如下:

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def oddEvenList(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            if not head or not head.next: return head
            odd_visit, even_visit = head, head.next
            head_odd, head_even = head, head.next
            visit, node_count = head.next.next, 0
            while visit:
                node_count += 1
                if node_count & 1:
                    odd_visit.next = visit
                    odd_visit = visit
                else:
                    even_visit.next = visit
                    even_visit = visit
                visit = visit.next
            odd_visit.next = even_visit.next = None
            odd_visit.next = head_even
            return head_odd

     

  • 相关阅读:
    day10
    day 09
    day08
    day07
    day6
    day5
    成员变量和局部变量
    (第五章)java面向对象之this的作用总结
    简单的音乐播放
    异步消息处理机制 简析
  • 原文地址:https://www.cnblogs.com/tallisHe/p/5313523.html
Copyright © 2011-2022 走看看