Python 如何实现单链表按照奇偶位置拆分成两个链表??

2025-03-05 02:27:48
推荐回答(5个)
回答1:

看见最佳答案回答的那么垃圾,真心伤心,python这个偷懒的编程语言,写的这冗余......

# coding=utf-8
nums = [1, 2, 3, 4, 5, 6, 7]

def split(nums):
    a, b = [], []
    [a.append(num) if nums.index(num) % 2 else b.append(num) for num in nums]
    return a, b

if __name__ == '__main__':
    a, b = split(nums)
    print('偶数角标链表:', a)
    print('奇数角标链表:', b)

回答2:

class Node:
    def __init__(self, val):
        self.val = val
        self.next = None
#构造链表1-->2-->3-->4-->5-->6-->7-->8
n8 = Node(8)
n7 = Node(7); n7.next = n8
n6 = Node(6); n6.next = n7
n5 = Node(5); n5.next = n6
n4 = Node(4); n4.next = n5
n3 = Node(3); n3.next = n4
n2 = Node(2); n2.next = n3
n1 = Node(1); n1.next = n2
#将节点存储在列表内
nodes = []
while n1:
    nodes.append(n1)
    n1 = n1.next
#改变节点的指向
for i in range(len(nodes)-1):
    if i == len(nodes)-2:
        nodes[i].next = None
    else:
        nodes[i].next = nodes[i+2]
#列表内前两个节点
oddNode = nodes[0]
evenNode = nodes[1]
#打印
while oddNode:
    print(oddNode.val, end=' ')
    oddNode = oddNode.next
print()
while evenNode:
    print(evenNode.val, end=' ')
    evenNode = evenNode.next

看看,不懂再问

回答3:

#按照链表位置进行奇偶拆分

def alist(nums):
    for num in nums:
        nums_index = nums.index(num)
        if nums_index % 2:
            a.append(num)
        else:
            b.append(num)
    return a, b


if __name__ == '__main__':
    nums = [1, 2, 3, 4, 5]
    a = []
    b = []
    alist(nums)
    print('我是偶数链表:', a)
    print('我是奇数链表:', b)

回答4:

#!/usr/bin/env python#coding = utf-8class Node: def __init__(self,data=None,next = None): self.data = data self.next = next def rev(link): pre = link cur = link.next pre.next = None while cur: temp = cur.next cur.next = pre pre =cur cur = temp return pre if __name__ == '__main__': link = Node(1, Node(2, Node(3, Node(4, Node(5, Node(6, Node(7, Node(8, Node(9))))))))) root = rev(link) while root: print(root.data) root =root.next

回答5:

a = ['1','2','3','4','5','6']
b = a[::2]
c = a[1::2]
print(b,c)