用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - python代码库

python奇偶链表

2024-04-24 作者: Python自学举报

[python]代码库

#给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。这里的奇数节点和偶数节点指的是节点编号的奇偶性,不是值的奇偶性。
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def oddEvenList(head):
    if not head:
        return head

    odd = head
    even = head.next
    even_head = even

    while even and even.next:
        odd.next = even.next
        odd = odd.next
        even.next = odd.next
        even = even.next

    odd.next = even_head
    return head


# Test Cases
def createLinkedList(arr):
    if not arr:
        return None
    head = ListNode(arr[0])
    curr = head
    for i in range(1, len(arr)):
        curr.next = ListNode(arr[i])
        curr = curr.next
    return head


def printLinkedList(head):
    if not head:
        return
    curr = head
    while curr:
        print(curr.val, end=" ")
        curr = curr.next
    print()


# Test Case 1
arr = [1, 2, 3, 4, 5]
head = createLinkedList(arr)
print("Input:")
printLinkedList(head)
head = oddEvenList(head)
print("Output:")
printLinkedList(head)

# Test Case 2
arr = [2, 1, 3, 5, 6, 4, 7]
head = createLinkedList(arr)
print("Input:")
printLinkedList(head)
head = oddEvenList(head)
print("Output:")
printLinkedList(head)


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...