zoukankan      html  css  js  c++  java
  • 链表之单向链表(python)

    链表中最简单的一种是单向链表,它包含两个域,一个信息域和一个指针域。这个链接指向列表中的下一个节点,而最后一个节点则指向一个空值。

    python代码实现:

    # 链表中的节点的数据结构
    class ListNode(object):
        def __init__(self, x):
            self.val = x
            self.next = None
    # 实例化
    A = ListNode('a')
    B = ListNode('b')
    C = ListNode('c')
    A.next = B
    B.next = C
    
    # 这样,一条链表就形成了。
    # 'a' -> 'b' -> 'c'

    # 遍历链表
    tmp = A
    while tmp != None:
        print(tmp.val)
        tmp = tmp.next
    
    # 递归遍历链表
    def listorder(head):
        if head:
            print(head.val)
            listorder(head.next)
    
    listorder(A)

    翻转一条单向链表:

    需求:

    Input: 1->2->3->4->5->NULL
    Output: 5->4->3->2->1->NULL

    class ListNode(object):
        def __init__(self, x):
            self.val = x
            self.next = None
    
    class Solution(object):
        def reverseList(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            dummy = head
            tmp = dummy
    
            while head and head.next != None:
                dummy = head.next
                head.next = dummy.next
                dummy.next = tmp
                tmp = dummy
            return dummy
    
    head = ListNode(1)
    head.next = ListNode(2)
    head.next.next = ListNode(3)
    head.next.next.next = ListNode(4)
    head.next.next.next.next = ListNode(5)
    
    solution = Solution()
    reverse_head = solution.reverseList(head)
    tmp = reverse_head
    while tmp:
        print(tmp.val)
        tmp = tmp.next


  • 相关阅读:
    【POJ1961 Period】【KMP】
    浅谈KMP算法
    【关于动态开点线段树】
    【POJ3349 Snowflake Snow Snowflakes】【Hash表】
    【NOI 2002 银河英雄传说】【带权并查集】
    路径问题
    group_concat函数详解
    MySQL中GROUP_CONCAT中排序
    怎么实现CSS限制字数,超出部份显示点点点.
    jsp去掉小数点
  • 原文地址:https://www.cnblogs.com/guo-s/p/12505334.html
Copyright © 2011-2022 走看看