数据结构与算法之链表 链表编程题 代码模板总结

数据结构与算法阿木 发布于 2025-07-11 8 次阅读


链表编程题:代码模板总结

链表是一种常见的基础数据结构,它由一系列节点组成,每个节点包含数据和指向下一个节点的指针。链表在计算机科学中有着广泛的应用,如实现栈、队列、哈希表等高级数据结构。本文将围绕链表编程题,总结一些常见的代码模板,帮助读者更好地理解和实现链表相关的算法。

一、链表的基本操作

在开始具体的编程题之前,我们首先需要了解链表的基本操作,包括创建链表、插入节点、删除节点、查找节点、遍历链表等。

1. 创建链表

python

class ListNode:


def __init__(self, value=0, next=None):


self.value = value


self.next = next

def create_linked_list(values):


if not values:


return None


head = ListNode(values[0])


current = head


for value in values[1:]:


current.next = ListNode(value)


current = current.next


return head


2. 插入节点

python

def insert_node(head, value, position):


new_node = ListNode(value)


if position == 0:


new_node.next = head


return new_node


current = head


for _ in range(position - 1):


if current is None:


return head


current = current.next


new_node.next = current.next


current.next = new_node


return head


3. 删除节点

python

def delete_node(head, position):


if position == 0:


return head.next


current = head


for _ in range(position - 1):


if current is None:


return head


current = current.next


if current.next is None:


return head


current.next = current.next.next


return head


4. 查找节点

python

def find_node(head, value):


current = head


while current:


if current.value == value:


return current


current = current.next


return None


5. 遍历链表

python

def traverse_linked_list(head):


current = head


while current:


print(current.value, end=' ')


current = current.next


print()


二、链表编程题代码模板

以下是一些常见的链表编程题及其代码模板:

1. 反转链表

python

def reverse_linked_list(head):


prev = None


current = head


while current:


next_node = current.next


current.next = prev


prev = current


current = next_node


return prev


2. 合并两个有序链表

python

def merge_sorted_linked_lists(l1, l2):


dummy = ListNode()


tail = dummy


while l1 and l2:


if l1.value < l2.value:


tail.next = l1


l1 = l1.next


else:


tail.next = l2


l2 = l2.next


tail = tail.next


tail.next = l1 or l2


return dummy.next


3. 删除链表的倒数第N个节点

python

def remove_nth_from_end(head, n):


dummy = ListNode(0)


dummy.next = head


slow = fast = dummy


for _ in range(n):


fast = fast.next


while fast:


slow = slow.next


fast = fast.next


slow.next = slow.next.next


return dummy.next


4. 判断链表是否有环

python

def has_cycle(head):


slow = fast = head


while fast and fast.next:


slow = slow.next


fast = fast.next.next


if slow == fast:


return True


return False


5. 链表中的两数相加

python

def add_two_numbers(l1, l2):


dummy = ListNode(0)


current = dummy


carry = 0


while l1 or l2 or carry:


val1, val2 = l1.value if l1 else 0, l2.value if l2 else 0


total = val1 + val2 + carry


carry = total // 10


current.next = ListNode(total % 10)


current = current.next


if l1:


l1 = l1.next


if l2:


l2 = l2.next


return dummy.next


三、总结

本文总结了链表编程题的一些常见代码模板,包括链表的基本操作和几个典型的编程题。通过学习和掌握这些模板,读者可以更好地应对链表相关的编程挑战。在实际编程过程中,可以根据具体问题对模板进行修改和优化,以达到最佳效果。