题目描述:
给定链表L0 —> L1 —> L2 .....Ln-1 —> Ln,把链表重新排序为L0 —> Ln —> L1 —> Ln-1 —>L2 —> Ln-2......
要求:
(1)在原来链表的基础上进行排序,即不能申请新的节点
(2)只能修改节点的next域,不能修改数据域
解题思路分析:
(1)首先找到链表的中间节点
(2)对链表的后半部分进行逆序
(3)把链表的前半部分和逆序后的后半部分进行合并
代码实现:
class LNode:
def __init__(self, item):
self.data = item
self.next = None
def FindMiddleNode(head):
if head is None or head.next is None:
return head
fast = head
slow = head
while fast is not None and fast.next is not None:
slowpre = slow
slow = slow.next
fast = fast.next.next
slowpre.next = None
return slow
#对不带头单链表进行翻转
def Reverse(head):
if head is None or head.next is None:
return head
pre = head
cur = head.next
next = cur.next
pre.next = None
while cur is not None:
next = cur.next
cur.next = p

本文介绍了如何在不创建新节点且不修改数据的情况下,通过改变链表节点的next域,对链表进行重新排序。解题思路包括找到链表中间节点、逆序后半部分链表以及合并两部分链表。提供了相应的代码实现和执行结果。
最低0.47元/天 解锁文章
628

被折叠的 条评论
为什么被折叠?



