链表 剑指offer

题目:输入一个链表,从尾到头打印链表每个节点的值

1.使用list,将所有元素放入后翻转打印

# class ListNode:

#    def __init__(self, x):

#        self.val = x

#        self.next = None

 

class Solution:

    #返回从尾部到头部的列表值序列,例如[1,2,3]

   def printListFromTailToHead(self, listNode):

       l=[] 

       while listNode: 

           l.append(listNode.val) 

           listNode=listNode.next 

       l.reverse() 

       return l 

2. 采用栈这种后进先出的性质

3. 递归思想

class Solution: 

# 返回从尾部到头部的列表值序列,例如[1,2,3] 

def printListFromTailToHead(self, listNode): 

    # write code here 

    if listNode is None: 

      return [] 

return  self.printListFromTailToHead(listNode.next)+ [listNode.val]

题目2输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则

1.非递归解法

class ListNode:

    def __init__(self, x):

        self.val = x

        self.next = None

       

class Solution:

    #返回合并后列表

   def Merge(self, pHead1, pHead2):

       p = ListNode(0)

       pHead = p

       while pHead1 and pHead2:

           if pHead1.val <= pHead2.val:

                p.next = pHead1

                pHead1 = pHead1.next

           else:

                p.next = pHead2

                pHead2 = pHead2.next

           p = p.next

       if pHead1:

           p.next = pHead1

       elif pHead2:

           p.next = pHead2

       return pHead.next

 

题目3:输入一个链表,输出该链表中倒数第k个"结点"。不是结点值

思路1:将所有节点存入list数组后,取-k

class ListNode:

   def __init__(self, x):

       self.val = x

       self.next = None

class Solution:

   def FindKthToTail(self, head, k):

       out = [] 

       while head:

           out.append(head.val)

           head = head.next

       if k>len(out) or k<1:

           return

       num = out[-k]

       return num

 

思路2:设置快慢指针,让快指针先走k-1步,然后同时走,当快指针到达链表尾部了,慢指针就是所需节点

# class ListNode:

#     def__init__(self, x):

#         self.val= x

#        self.next = None

 

class Solution:

    defFindKthToTail(self, head, k):

        ifhead==None or k<=0:

            returnNone

        fast_p =head

        slow_p =head

       

        count = 1                   #头节点占一个节点

        whilecount<k:

            iffast_p.next is not None:

               fast_p = fast_p.next

               count += 1

            else:

               return

       

        whilefast_p.next is not None:

            fast_p= fast_p.next

            slow_p = slow_p.next

        return slow_p

题目4:输入一个链表,反转链表后,输出新链表的表头。

class Solution:

    # 返回ListNode

    defReverseList(self, pHead):

        ifpHead==None or pHead.next==None:

            returnpHead

       

        last =None

        cur = pHead

        while cur:

            tmp =cur.next

           cur.next = last

            last =cur

            cur =tmp

        return last


图解:


猜你喜欢

转载自blog.csdn.net/eat_shopping/article/details/80835636