Python - 实现简单单链表

代码如下:

class Node():
    def __init__(self,pvalue,pnext = None):
        self.pvalue = pvalue
        self.pnext = pnext

def 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 root

def PrintLinkedList(head):
    p = head
    while p != None:
        print(p.pvalue)
        p = p.pnext

def LenLinkedList(head):
    p = head
    c = 0
    while p != None:
        c += 1
        p = p.pnext
    return c

def 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 head

def 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 head


if __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

你可能感兴趣的:(Python,Algorithm,Python,Coding)