重排链表python实现
时间: 2023-09-14 17:06:17 浏览: 115
重排链表的python实现可以使用栈来实现。首先,将链表中的节点压入栈中,然后按照指定的规则依次从栈中出栈,重新连接节点。
代码示例如下:
```python
class Solution(object):
def reorderList(self, head):
if not head:
return
stack = []
s = head
while s.next:
stack.append(s.next)
s = s.next
s = head
n = 0
while stack:
if n % 2 == 0:
one = stack.pop()
else:
one = stack.pop(0)
one.next = None
s.next = one
s = s.next
n += 1
```
这段代码中,首先判断头节点是否为空,然后初始化一个栈,并将链表中的其它节点压入栈中。然后,重新遍历链表,根据指定的规则从栈中出栈,并重新连接节点。
这样就能实现重排链表的功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [LeetCode: 重排链表 python实现](https://blog.csdn.net/weixin_43786241/article/details/105752892)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [L2-022 重排链表(Python3)](https://blog.csdn.net/weixin_55730361/article/details/126516893)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文