剑指offer13~15题

版权声明:本博所有原创文章,欢迎转载,转载请注明出处 https://blog.csdn.net/qq_34553043/article/details/82990062

调整数组顺序使奇数位于偶数前面

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

class Solution:
    def reOrderArray(self, array):
        # write code here
        odd = []
        even = []
        for d in array:
            if d % 2 == 1:
                odd.append(d)
            else:
                even.append(d)
        return odd + even

链表中倒数第k个结点

输入一个链表,输出该链表中倒数第k个结点。

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        arr=[]
        while head!=None:
            arr.append(head)
            head=head.next
        if k>len(arr) or k<1:
            return
        return arr[-k]

反转链表

输入一个链表,反转链表后,输出新链表的表头。

class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if not pHead or not pHead.next:
            return pHead
        last = None
        while pHead:
            tmp = pHead.next
            pHead.next = last
            last = pHead
            pHead = tmp
            
        return last     

猜你喜欢

转载自blog.csdn.net/qq_34553043/article/details/82990062
今日推荐