鏈表題目匯總(python3)


1、從頭到尾打印鏈表

輸入一個鏈表,按鏈表值從尾到頭的順序返回一個ArrayList。

# -*- coding:utf-8 -*-
class ListNode:
     def __init__(self, x):
         self.val = x
         self.next = None

class Solution:
    def printListFromTailToHead(self, listNode):
        l =[]
        while listNode:
            l.append(listNode.val)
            listNode = listNode.next
        return l[::-1]

2、鏈表中倒數第k個節點

輸入一個鏈表,輸出該鏈表中倒數第k個結點。

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def FindKthToTail(self, head, k):
        node_list = []
        while head:
            node_list.append(head)
            head = head.next
        if k < 1 or k > len(node_list):
            return
        return node_list[-k]

3、反轉鏈表

輸入一個鏈表,反轉鏈表后,輸出新鏈表的表頭。

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
        
class Solution:
    def ReverseList(self, pHead):
        if pHead is None or pHead.next is None:
            return pHead
        pre = None
        cur = pHead
        while cur:
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp
        return pre

 

待續...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM