zoukankan      html  css  js  c++  java
  • Leetcode代码补全——链表

    通过补全代码可以更深刻的体会到,链表就是一个存储方式,通过一单元的存储指向下一单元,而查看单元内容通过头部开始的指针依次遍历。这是leetcode里融合两个链表的题目,具体代码如下:

    #encoding=utf-8

    class ListNode(object):

        def __init__(self, x):

            self.val = x

            self.next = None

            self.root = None

    #添加链表节点函数

        def addNode(self, val):

            if self.root==None:

                self.root= ListNode(x=val)

                return self.root

            else:

          # 有头结点,则需要遍历到尾部节点,进行链表增加操作

                cursor = self.root

                while cursor.next!= None:

                    cursor = cursor.next

                cursor.next = ListNode(x=val)

                return self.root

    #下面就是题目具体解决过程 

    class Solution(object):

        def mergeTwoLists(self, l1, l2):

            """

            :type l1: ListNode

            :type l2: ListNode

            :rtype: ListNode

            """

            head=ListNode(0)

            cur=head

            

            while(l1!=None and l2!=None):

                if l1.val<l2.val:

                    cur.next=l1

                    l1=l1.next

                else:

                    cur.next=l2

                    l2=l2.next

                #cur.next.next=None

                cur=cur.next

            if l1!=None:

                cur.next=l1

            else:

                cur.next=l2

            return head.next

    #下面也是leetcode省略部分,实例化两个链表。添加节点,进行融合操作 

    a=ListNode(1)

    b=ListNode(1)

    print a.addNode(3).addNode(4)

    print b.addNode(2).addNode(4)

    c=Solution()

    print c.mergeTwoLists(a,b)

  • 相关阅读:
    VRRP(Virtual Router Redundancy Protocol)业界标准
    CISCO快速转发
    89、C++中将临时变量作为返回值时的处理过程
    87、C++函数调用的压栈过程
    82、类什么时候会析构?
    84、智能指针的原理、常用的智能指针及实现
    81、构造函数一般不定义为虚函数的原因
    80、构造函数析构函数可否抛出异常
    79、虚析构函数的作用,父类的析构函数是否要设置为虚函数?
    78、构造函数、析构函数的执行顺序?
  • 原文地址:https://www.cnblogs.com/garvicker/p/9044330.html
Copyright © 2011-2022 走看看