hot100链表题
时间: 2025-05-31 12:42:12 浏览: 39
### hot100 链表算法题练习
以下是与 LeetCode Hot 100 中链表相关的经典算法题目及其简要说明:
#### 1. **两数相加 (Add Two Numbers)**
这道题要求实现一个函数,输入两个非空链表,表示两个非负整数。这些数字以逆序方式存储在链表中,每个节点包含一位数字。返回一个新的链表,代表这两个数之和[^1]。
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode()
current = dummy
carry = 0
while l1 or l2 or carry:
v1 = l1.val if l1 else 0
v2 = l2.val if l2 else 0
total = v1 + v2 + carry
carry = total // 10
current.next = ListNode(total % 10)
current = current.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummy.next
```
---
#### 2. **删除链表的倒数第 N 个结点 (Remove Nth Node From End of List)**
此题的目标是从单链表中移除倒数第 n 个节点,并返回修改后的链表头指针。
```python
def removeNthFromEnd(head: ListNode, n: int) -> ListNode:
dummy = ListNode(next=head)
fast = slow = dummy
for _ in range(n + 1):
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
```
---
#### 3. **合并两个有序链表 (Merge Two Sorted Lists)**
将两个升序链表合并为一个新的升序链表并返回。新链表应由原链表中的节点组成[^1]。
```python
def mergeTwoLists(list1: ListNode, list2: ListNode) -> ListNode:
dummy = ListNode()
tail = dummy
while list1 and list2:
if list1.val < list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.next
tail.next = list1 if list1 else list2
return dummy.next
```
---
#### 4. **环形链表 (Linked List Cycle)**
判断给定链表是否存在环。如果存在环,则返回 `True`;否则返回 `False`[^2]。
```python
def hasCycle(head: ListNode) -> bool:
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
```
---
#### 5. **反转链表 (Reverse Linked List)**
反转一个单链表并返回新的头节点。
```python
def reverseList(head: ListNode) -> ListNode:
prev = None
curr = head
while curr:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev
```
---
#### 6. **回文链表 (Palindrome Linked List)**
检查一个链表是否为回文结构。
```python
def isPalindrome(head: ListNode) -> bool:
values = []
while head:
values.append(head.val)
head = head.next
return values == values[::-1]
```
---
以上是部分经典的链表算法题目,适合初学者到中级水平的开发者进行练习。每一道题都具有一定的挑战性和实际应用价值。
---
###
阅读全文
相关推荐



















