文章来源:https://www.toymoban.com/news/detail-688858.html
思路:分别处理奇偶,保存奇偶的第一个和最后一个节点,注意最后链接的时候需要把偶数的next去掉再拼接不然就成环了文章来源地址https://www.toymoban.com/news/detail-688858.html
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head or not head.next or not head.next.next:
return head
first_odd = head
first_even = head.next
last_odd = head
last_even = head.next
current_node = first_even.next
node_num = 3
while current_node:
next_node = current_node.next
if node_num % 2 == 1:
last_odd.next = current_node
last_odd=current_node
else:
last_even.next = current_node
last_even=current_node
current_node = next_node
node_num += 1
last_odd.next=first_even
last_even.next=None
return first_odd
到了这里,关于Leetcode328 奇偶链表的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!