单链表分段逆转,给定一个带头结点的单链表和一个整数K,要求你将链表中的每K个结点做一次逆转。要求完整代码可运行
时间: 2024-06-13 10:05:11 浏览: 127
单链表分段逆转,给定一个带头结点的单链表和一个整数K,要求你将链表中的每K个结点做一次逆转。以下是完整可运行的Python代码:
```python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def reverseKGroup(head: ListNode, k: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
pre = dummy
end = dummy
while end.next:
for i in range(k):
if end:
end = end.next
if not end:
break
start = pre.next
next_node = end.next
end.next = None
pre.next = reverse(start)
start.next = next_node
pre = start
end = pre
return dummy.next
def reverse(head: ListNode) -> ListNode:
pre = None
cur = head
while cur:
next_node = cur.next
cur.next = pre
pre = cur
cur = next_node
return pre
```
阅读全文