已知链表first将链表前后倒置
时间: 2024-01-04 17:45:08 浏览: 85
以下是Python实现:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
prev = None
curr = head
while curr is not None:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
```
这里的 `reverseList` 函数使用了迭代的方式实现链表的前后倒置。具体来说,我们用 `prev` 来记录当前节点的前一个节点,用 `curr` 来记录当前节点。然后我们不断地遍历链表,每次将 `curr.next` 指向 `prev`,然后更新 `prev` 和 `curr`,直到 `curr` 变成了 `None`,此时 `prev` 就是新的头节点。
使用方法:
```python
# 创建链表 1 -> 2 -> 3 -> 4 -> 5
head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
# 前后倒置
new_head = reverseList(head)
# 输出倒置后的链表
while new_head is not None:
print(new_head.val, end=" ")
new_head = new_head.next
# 输出:5 4 3 2 1
```
阅读全文