zoukankan      html  css  js  c++  java
  • leetcode-mid-Linked list-328 Odd Even Linked List-NO

    mycode 

    # 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
            """
            Odd = head
            Even = dummyeven = head.next
            while Even and Even.next:
                print(Even.val,Odd.val,Odd.next.val,Odd.next.next.val)
                Even.next = Even.next.next #3 6 7
                print(Even.next.val,Odd.next.val,Odd.next.next.val)
                Even = Even.next
                Odd.next = Odd.next.next # 5 4 Null
                print(Odd.next.val,Odd.next.val,Odd.next.next.val)
                Odd = Odd.next 
                print(Even.val,Odd.val)
            Odd.next = dummyeven #因为无论even=None还是Even.next=None,其实在没有Even = Even.next之前,Even.next=head链中它的下一个,所以不用分类讨论加不加None
            
            return head
        

    错误原因:Even节点变化之后,Odd取next和.next.next时,链表都已经变化了

    参考:保证链表取值过程中相对顺序不乱!

    # 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:
                return head
            Odd = head
            Even = dummyeven = head.next
            while Even and Even.next:
                Odd.next = Even.next
                Odd = Odd.next 
                Even.next = Odd.next #3 6 7
                Even = Even.next    
            Odd.next = dummyeven #因为无论even=None还是Even.next=None,其实在没有Even = Even.next之前,Even.next=head链中它的下一个,所以不用分类讨论加不加None 
            return head
        
           
  • 相关阅读:
    揉碎HTTP编码过程,从此不乱码
    Eclipse与IDEA配置tomcat
    JavaWEB入门
    网络编程-socket
    Java
    Mysql存储过程 —— SEQUENCE的实现
    Java Servlet 2.5 设置 cookie httponly
    CountDownLatch和CyclicBarrier 区别
    ply python 图片压缩 图片裁剪 旋转
    各种正则大杂烩,正则手机,正则邮箱
  • 原文地址:https://www.cnblogs.com/rosyYY/p/10966773.html
Copyright © 2011-2022 走看看