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 binary_search(list,item): low = 0 high = len(list)-1 while low<=high: mid = (low+high)/2 guess = list[mid] if guess>item: high = mid-1 elif guess<item: low = mid+1 else: return mid return None mylist = [1,3,5,7,9] print binary_search(mylist,3)
本文首发于python黑洞网,博客园同步更新

更多精彩