链表15--重排链表

1、题目:


Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

2、解答:该题目的意思是 链表原地修改。问题的解可以分为三步:1、找到链表的中间结点 2、把中间结点到尾结点进行反转,也就是链表的指向反转 3、合并两个链表


3、C++代码

class Solution {
public:
    void reorderList(ListNode* head) {
        ListNode *slow ,*fast;
        ListNode *preNode,*curNode;
        
        if(!head || !head->next){
            return ;
        }else{
            //求中间结点
            slow = head;
            fast = head->next;
            while(fast && fast->next){
                slow = slow->next;
                fast = fast->next->next;
            }
            
            fast = slow->next;   //fast to end 
            slow->next = NULL;
            preNode = NULL;
            //第二个链表的逆序
            while(fast){
               curNode = fast->next;
               fast->next = preNode;
                preNode = fast;
                fast = curNode;
            }
            
            fast = preNode;
            slow = head;
            //合并两个链表
            while(fast){
                ListNode *temp1 = slow->next;
                ListNode *temp2 = fast->next;
                fast->next = slow->next;
                slow->next = fast;
                slow = temp1;
                fast = temp2;
            }
            
        }
    }
};

python代码

class Solution:
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: void Do not return anything, modify head in-place instead.
        """
        if head is None or head.next is None:
            return    
        else:
            //找链表的中间位置
            slow,fast = head,head.next
            while fast and fast.next:
                slow = slow.next
                fast = fast.next.next
            
            fast = slow.next
            slow.next = None
            
            preNode = None
            
            while fast:
                temp = fast.next
                fast.next = preNode
                preNode = fast
                fast = temp
                
            slow = head
            fast = preNode
            while fast:
                temp1 = slow.next
                temp2 = fast.next
                fast.next = slow.next
                slow.next = fast
                slow = temp1
                fast = temp2
            return 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值