91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

如何利用雙重指針實現鏈表操作

c++
小樊
83
2024-09-24 23:25:21
欄目: 編程語言

雙重指針(也稱為啞指針或哨兵節點)在鏈表操作中非常有用,特別是當需要簡化邊界條件處理、提高代碼可讀性和減少錯誤時。以下是使用雙重指針實現鏈表操作的一些建議:

  1. 合并兩個有序鏈表:
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
    dummy = ListNode(-1)
    current = dummy

    while l1 and l2:
        if l1.val < l2.val:
            current.next = l1
            l1 = l1.next
        else:
            current.next = l2
            l2 = l2.next
        current = current.next

    if l1:
        current.next = l1
    elif l2:
        current.next = l2

    return dummy.next
  1. 刪除鏈表中的重復元素:
def deleteDuplicates(head: ListNode) -> ListNode:
    if not head or not head.next:
        return head

    dummy = ListNode(-1)
    dummy.next = head
    current = dummy
    prev = dummy

    while current.next and current.next.next:
        if current.next.val == current.next.next.val:
            while current.next and current.next.val == current.next.next.val:
                current = current.next
            prev.next = current.next
        else:
            prev = current
            current = current.next

    return dummy.next
  1. 反轉鏈表:
def reverseList(head: ListNode) -> ListNode:
    prev = None
    current = head

    while current:
        next_node = current.next
        current.next = prev
        prev = current
        current = next_node

    return prev
  1. 找到鏈表的中間節點:
def middleNode(head: ListNode) -> ListNode:
    slow = head
    fast = head

    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

    return slow
  1. 刪除鏈表的倒數第k個節點:
def removeNthFromEnd(head: ListNode, k: int) -> ListNode:
    dummy = ListNode(-1)
    dummy.next = head
    first = dummy
    second = dummy

    for _ in range(k):
        first = first.next

    while first:
        first = first.next
        second = second.next

    second.next = second.next.next

    return dummy.next

這些示例展示了如何使用雙重指針簡化鏈表操作。在實際應用中,您可能需要根據具體需求調整代碼。

0
平湖市| 大丰市| 辽宁省| 兰坪| 灌云县| 浦江县| 西藏| 星座| 柳江县| 盐池县| 肥东县| 静乐县| 云龙县| 义马市| 察隅县| 靖江市| 白玉县| 香河县| 浮梁县| 石棉县| 镇雄县| 江孜县| 梁河县| 赤水市| 宁南县| 仲巴县| 叙永县| 盐边县| 钦州市| 宁化县| 同江市| 穆棱市| 古浪县| 松潘县| 南安市| 呼图壁县| 民和| 抚松县| 鹤庆县| 五莲县| 海原县|