头插法与迭代反转链表的区别:代码示例及详细解析
头插法和迭代反转链表是两种常见的链表操作方法,它们在功能上有所区别。
1. 头插法
头插法是一种用于构建链表的方法。它通过将新节点插入到链表头部来实现链表的构建。具体步骤如下:
- 创建一个新节点,并将新节点的 next 指针指向当前链表的头节点。
- 将新节点设置为链表的头节点。
- 重复上述步骤,直到所有元素都插入到链表中。
头插法代码示例(使用 Python 语言):
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def insertAtHead(head, val):
newNode = ListNode(val)
newNode.next = head
return newNode
# 示例用法
head = None
head = insertAtHead(head, 3)
head = insertAtHead(head, 2)
head = insertAtHead(head, 1)
2. 迭代反转链表
迭代反转链表是一种通过修改指针指向来实现链表反转的方法。具体步骤如下:
- 初始化三个指针,分别指向当前节点(cur)、当前节点的前一个节点(prev)和当前节点的后一个节点(next)。
- 在迭代过程中,先将当前节点的 next 指针指向 prev 节点,然后更新 prev、cur 和 next 指针。
- 重复上述步骤,直到遍历完整个链表。
迭代反转链表代码示例(使用 Python 语言):
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head):
prev = None
cur = head
while cur:
next = cur.next
cur.next = prev
prev = cur
cur = next
return prev
# 示例用法
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
reversedHead = reverseList(head)
总结
头插法用于构建链表,迭代反转链表用于反转已存在的链表。这两种方法在实现原理和应用场景上都有所区别,需要根据具体的需求选择合适的方法。
原文地址: https://www.cveoy.top/t/topic/p9vM 著作权归作者所有。请勿转载和采集!