Python

来源:互联网 发布:编程 开发 编辑:程序博客网 时间:2024/06/15 21:16

代码如下:

class Node():    def __init__(self,pvalue,pnext = None):        self.pvalue = pvalue        self.pnext = pnextdef CreateLinkedList(n):    if n <= 0 :        return False    if n == 1 :        return Node(1)    else:        root = Node(1)  # init the root node        tmp = root        for i in range(2,n+1):            tmp.pnext = Node(i)            tmp = tmp.pnext    return rootdef PrintLinkedList(head):    p = head    while p != None:        print(p.pvalue)        p = p.pnextdef LenLinkedList(head):    p = head    c = 0    while p != None:        c += 1        p = p.pnext    return cdef InsertLinkedList(head,n):    if n < 1 or n > LenLinkedList(head):        return False    p = head    for i in range(1,n-1):        p = p.pnext    v = int(input('Please input the number:'))    t = Node(v)    t.pnext = p.pnext    p.pnext = t    return headdef DeleteLinkedList(head,n):    if n < 1 or n > LenLinkedList(head):        return False    elif n == 1:        head = head.pnext    else :        p = head        for i in range(1,n-1):            p = p.pnext        q = p.pnext        p.pnext = q.pnext    return headif __name__=='__main__':    print("Create a linklist:")    head = CreateLinkedList(5)    PrintLinkedList(head)    print("___________________________")    print()    n = int(input("Please input the index of insert:"))    InsertLinkedList(head,n)    PrintLinkedList(head)    print("___________________________")    print()    n1 = int(input("Please input the index of delete:"))    DeleteLinkedList(head,n1)    PrintLinkedList(head)    print("___________________________")    print()    print('The LinkedList\'s length is:{0}'.format(LenLinkedList(head)))

Result:

Create a linklist: 1 2 3 4 5


Please input the index of insert:2
Please input the number:34
1 34 2 3 4 5


Please input the index of delete:4
1 34 2 4 5


The LinkedList’s length is:5

原创粉丝点击