python 数据结构

前端之家收集整理的这篇文章主要介绍了python 数据结构前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

链表成对调换

class ListNode:
    def __init__(self,x):
        self.val = x
        self.next = None

class Solution:
    # @param a ListNode
    # @return a ListNode
    def swapPairs(self,head):
        if head != None and head.next != None:
            next = head.next
            head.next = self.swapPairs(next.next)
            next.next = head
            return next
        return head

单链表反转

class Node(object):
    def __init__(self,data=None,next=None):
        self.data = data
        self.next = next

link = Node(1,Node(2,Node(3,Node(4,Node(5,Node(6,Node(7,Node(8,Node(9)))))))))

def rev(link):
    pre = link
    cur = link.next
    pre.next = None
    while cur:
        tmp = cur.next
        cur.next = pre
        pre = cur
        cur = tmp
    return pre

root = rev(link)
while root:
    print root.data
    root = root.next

快速排序

def quicksort(list):
    if len(list)<2:
        return list
    else:
        midpivot = list[0]
        lessbeforemidpivot = [i for i in list[1:] if i<=midpivot]
        biggerafterpivot = [i for i in list[1:] if i > midpivot]
        finallylist = quicksort(lessbeforemidpivot)+[midpivot]+quicksort(biggerafterpivot)
        return finallylist

print quicksort([2,4,6,7,1,2,5])

二分搜索

 
#coding:utf-8
def @H_502_234@binary_search(list,item):
    low = @H_502_234@0
    high = @H_502_234@len(list)-1
    while @H_502_234@low<=high:
        mid = @H_502_234@(low+high)/2
        guess = @H_502_234@list[mid]
        if @H_502_234@guess>item:
            high = @H_502_234@mid-1
        elif @H_502_234@guess<item:
            low = @H_502_234@mid+1
        else:@H_502_234@
            return @H_502_234@mid
    return @H_502_234@None
mylist = @H_502_234@[1,3,5,7,9]
print @H_502_234@binary_search(mylist,3)

 

本文首发于python黑洞网博客园同步更新

猜你在找的Python相关文章