单链表-Python操作

来源:互联网 发布:帝国cms添加播放器 编辑:程序博客网 时间:2024/04/29 11:15

     链表是数据结构中最基本常用的,C++语言中单链表是利用指针操作实现的,python作为面向对象编程的,可以使用创建一个Node类来实现链表,利用类的属性引用来代替指针操作。

    下面我们创建了一个节点类,然后编写了几个链表操作,包括创建,插入,删除,输出等:

class Node():     # 初始化 构造函数    def __init__(self,value,next=None):        self.value=value        self.next=nextdef Creatlist(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 root            # 返回根节点def printlist(head):       # 打印链表    p=head    while p!=None:        print p.value        p=p.nextdef listlen(head):       # 链表长度    c=0    p=head    while p!=None:        c=c+1        p=p.next    return cdef insert(head,n):         # 在n的前面插入元素    if n<1 or n>listlen(head):        return    p=head    for i in range(1,n-1):  # 循环四次到达 5        p=p.next    a=raw_input("Enter a value:")    t=Node(value=a)    t.next=p.next     # 这里注意    p.next=t    return head       # 把6放在t的后面 t放在原先p的后面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     # 循环到达 2次         q=p.next        p.next=q.next    # 把5放在3的后面    return headdef main():    print "Create a linklist"    head=Creatlist(7)    printlist(head)    print    print "___________________________"    n1=raw_input("Enter the index to insert")    n1=int(n1)    insert(head,n1)    printlist(head)    print    print "___________________________"    n2=raw_input("Enter the index to delete")    n2=int(n2)    dellist(head,n2)    printlist(head)if __name__=='__main__':  main()   # 主函数调用


运行结果如下:
run C:\\Anaconda\\node.pyCreate a linklist1234567___________________________Enter the index to insert 6Enter a value:99123459967___________________________Enter the index to delete 412359967



参考资料:http://blog.csdn.net/u010786109/article/details/40650609


0 0
原创粉丝点击