zl程序教程

您现在的位置是:首页 >  其他

当前栏目

【LeetCode】328.奇偶链表

2023-09-14 09:13:25 时间

1.题目

在这里插入图片描述

2.分析

按照奇偶位置进行分割,然后再链接一下即可。

3.代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head:
            return head
        # 这题就可以按照奇偶链表的分割来做
        # 针对奇偶长度来判断
        h1 = h2 = head
        s1 = s2 = head
        h2 = h2.next
        s2 = s2.next
        pre = None
        while(h1 and h2):
            tmp1 = h2.next
            h1.next = h2.next
            pre = h1
            h1 = tmp1            
            if h2.next:                
                h2.next = h2.next.next
                h2 = h2.next            
        if h1: # 长度为奇数的链表需要考虑的问题
            pre = h1        
        pre.next = s2
        return s1