基于上述链表结构及操作,写一个代码实现链表反转
时间: 2023-05-29 18:01:57 浏览: 93
以下是Python示例代码:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head: ListNode) -> ListNode:
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
```
使用方法:
```python
# 创建链表
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node1.next = node2
node2.next = node3
node3.next = node4
# 反转链表
new_head = reverseList(node1)
```
上面代码将创建一个链表 1 → 2 → 3 → 4,然后使用 `reverseList` 函数对其进行反转,得到新的链表 4 → 3 → 2 → 1,存储在变量 `new_head` 中。
阅读全文