python 模拟链表

来源:互联网 发布:http默认端口号 编辑:程序博客网 时间:2024/06/08 19:02
class Node():    def __init__(self,value,next=None):        self.value = value        self.next  = next        def CreateList(n):    if n<=0:        return False    if n == 1:        return Node(1)    else:        root = Node(1)        tmp  = root        for i in range(2,n+1):            tmp.next = Node(i)            tmp      = tmp.next    return rootdef printList(head):    p = head    while p!=None:        print p.value        p = p.nextdef listLen(head):    cnt = 0    p   = head    while(p!=None):        p = p.next        cnt += 1    return cntdef insert(head,n):    if n<1 or n>listLen(head):        return    p = head    for i in range(1,n-1):        p = p.next    a = raw_input("Enter a value:")    t = Node(value = a)    t.next = p .next    p.next = t    return head    def dellist(head,n):    if n<1 or n>listLen(head):        return head    elif n is 1:        head = head.next    else:        p = head        for i in range(1,n-1):            p = p.next        q = p.next        p.next = q.next    return headdef mergeTwoLists(l1, l2):        if l1 is None:        return l2    if l2 is None:        return l1    pHead = Node(0)    if l1.value <l2.value:        pHead = l1        pHead.next = mergeTwoLists(l1.next,l2)    else:        pHead = l2        pHead.next = mergeTwoLists(l1,l2.next)    return pHead    if __name__ == "__main__":    print "Create a linklist"    head1 = CreateList(7)    head2 = CreateList(8)    head = mergeTwoLists(head1,head2)    printList(head)                                                                        

原创粉丝点击