题解 | 链表的奇偶重排-值存数组再填入新链表

链表的奇偶重排

https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @return ListNode类
#
class Solution:
    def oddEvenList(self , head: ListNode) -> ListNode:
        # write code here
        # 将奇数 偶数为的存入两个list中 再拼接出新的链表
        if not head  or not  head.next:
            return head 
        a_list=[]
        b_list=[]
        #print("aaaaaa")
        cur=head
        count =1
        while cur:
            if count%2==0:
                b_list.append(cur.val)
            else:
                a_list.append(cur.val)
            count+=1
            cur=cur.next
        print("-------",a_list,b_list)
        newhead=ListNode(0)
        cur=newhead
        for i in range(len(a_list)):
            cur.next=ListNode(a_list[i])
            cur=cur.next
        for i in range(len(b_list)):
            cur.next=ListNode(b_list[i])
            cur=cur.next
        return newhead.next 






全部评论

相关推荐

活泼的代码渣渣在泡池...:哈哈哈挺好的,我也上岸美团了,不说了,我又接了一单
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务