Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions problems/0024.两两交换链表中的节点.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,42 @@ class Solution:

```

```python
# 双指针
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return head

# 虚拟头节点
dummy_head = ListNode(0, head)
# 双指针,cur指向前面的节点,post指向后面的节点,循环从头节点开始
cur = head
post = dummy_head

# 如果遍历完所有节点则循环结束
while cur:
# 如果是奇数节点,会存在进入循环但是不需要调换的情况,那么就直接返回头节点
if not cur.next:
return dummy_head.next
# 交换节点
post.next = cur.next
cur.next = post.next.next
post.next.next = cur
# 更新指针
cur = cur.next
post = post.next.next

return dummy_head.next
```



### Go:

```go
Expand Down
3 changes: 1 addition & 2 deletions problems/链表总结篇.md
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why

Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

## 链表经典题目

### 虚拟头结点
### 虚拟头节点

在[链表:听说用虚拟头节点会方便很多?](https://programmercarl.com/0203.移除链表元素.html)中,我们讲解了链表操作中一个非常重要的技巧:虚拟头节点。

Expand Down Expand Up @@ -95,4 +95,3 @@