python实现单链表的建立、访问和排序

第一个比较完整的python程序,排序效率不是很好,待改进!

采用类的方式实现,包含两个文件

list2:定义listNode类及createList、scanList和sortList方法

test2:对listNode类的调用

class listNode:
    def __init__(self,x):
        self.val = x
        self.next  = None        
    def createList(self,a):
        if a is None:
           print 'no elements'
           return
        head=listNode(a[0])
        p=head
        i=1
        n=len(a)
        while i<n:
            t=listNode(a[i])
            p.next=t
            p=t
            i=i+1
        return head
    def scanList(self,head):
       if head is None:
          print "no elements"
          return
       print head.val
       while head.next:
             p=head.next
             print p.val
             head=p             
    def sortList(self, head):
        if head is None or head.next is None:
            return head
        mid = (head.val + head.next.val) / 2
        if head.val > head.next.val:
            lhead, rhead = head.next, head
        else:
            lhead, rhead = head, head.next
        lit, rit = lhead, rhead
        it = head.next.next       
        while it is not None:
            if it.val > mid:
                rit.next = it
                rit = it                
            else:
                lit.next = it
                lit = it 
            it = it.next
        lit.next, rit.next = None, None
        lhead = self.sortList(lhead)
        rhead = self.sortList(rhead)
        it = lhead
        while it.next is not None:
            it = it.next
        it.next = rhead
        return lhead

test2.py

import list2
l=list2.listNode(0)
a=[2,5,9,3,6,1,0,7,4,19]
head=l.createList(a)
print 'old list:'
l.scanList(head)
newhead=l.sortList(head)
print 'sorted list:'
l.scanList(newhead)

你可能感兴趣的:(python实现单链表的建立、访问和排序)