Python 没有';我没有奇偶链接列表

Python 没有';我没有奇偶链接列表,python,linked-list,Python,Linked List,我在解决leetcode问题328。奇偶链表,我们必须首先在奇数索引和偶数索引上打印所有数字 class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def printList(self):

我在解决leetcode问题328。奇偶链表,我们必须首先在奇数索引和偶数索引上打印所有数字

class Node:  
    def __init__(self, data): 
        self.data = data   
        self.next = None

class LinkedList: 
    def __init__(self): 
        self.head = None

    def printList(self): 
        temp = self.head 
        while (temp): 
            print (temp.data) 
            temp = temp.next


    def oddEvenList(self):
        end = Node(self.head)
        temp = Node(self.head)
        #end = head
        #temp = head
        counter = 0

        while end.next is not None:
            end = end.next
            counter += 1 
        if((counter & 1) == 0):
            counter = counter //2
        else:
            counter =  (counter//2) + 1

        while counter != 0:
            end.next = temp.next
            temp.next = temp.next.next
            end.next.next = None
            end = end.next
            temp = temp.next
        return self.head

if __name__=='__main__': 

    # Start with the empty list 
    llist = LinkedList() 

    llist.head = Node(1) 
    second = Node(2) 
    third = Node(3)
    fourth = Node(4)
    fifth = Node(5)

    llist.head.next = second; 
    second.next = third;
    third.next = fourth
    fourth.next = fifth
    fifth.next = None

    llist.printList() 

    llist.oddEvenList()

    llist.printList()
逻辑是正确的,并且应该在我多次跟踪程序时起作用

我认为我的程序没有进入第一个while循环

while end.next is not None:
        end = end.next
        counter += 1 
我可以建议,是否有语法错误,我遗漏了,否则的逻辑是正确的程序

输入-1->2->3->4->5->Null 以上程序输出-1->2->3->4->5->Null


所需的输出-1->3->5->2->4->Null

您可以使用ListNode并以简单的方式生成它

def列表(self,head):
dummy1=奇数=列表节点(0)
dummy2=偶数=ListNode(0)
而负责人:
奇数。下一个=头
偶数.next=头.next
奇数=奇数
偶数
head=head.next.next如果没有
奇数.next=dummy2.next
返回dummy1.next

Hi@Rajan Pipaliya,记住我,再加上一些细节来解释答案:P.太好了,你的逻辑是正确的,但是你能解释一下我的错误吗@拉詹·皮帕利亚