MST

星途 面试题库

面试题:C语言指针在复杂数据结构中的内存管理应用

假设有一个链表数据结构,节点包含一个整数和一个指向下一个节点的指针。请编写代码实现链表的创建、插入节点和删除节点的操作,并确保在这些操作过程中内存管理的正确性。阐述在这些操作中指针是如何影响内存的分配与释放的。
38.2万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def create_linked_list(nums):
    if not nums:
        return None
    head = ListNode(nums[0])
    current = head
    for num in nums[1:]:
        current.next = ListNode(num)
        current = current.next
    return head


def insert_node(head, val, pos):
    new_node = ListNode(val)
    if pos == 0:
        new_node.next = head
        return new_node
    current = head
    count = 0
    while current and count < pos - 1:
        current = current.next
        count += 1
    if current:
        new_node.next = current.next
        current.next = new_node
    return head


def delete_node(head, val):
    if not head:
        return None
    if head.val == val:
        return head.next
    current = head
    while current.next and current.next.val != val:
        current = current.next
    if current.next:
        current.next = current.next.next
    return head


# 指针影响内存分配与释放的阐述:
# 创建链表时,每创建一个新节点,会为其分配内存空间,通过指针将节点连接起来。
# 插入节点时,先创建新节点分配内存,然后调整指针,将新节点接入链表,不会释放任何已分配内存。
# 删除节点时,通过调整指针绕过要删除的节点,原本该节点占用的内存需要手动释放(在C/C++中需手动delete,Python中有垃圾回收机制会自动回收不再被引用的对象内存),若不释放会导致内存泄漏。