143. 重排链表

在这里插入图片描述
方法一:基本方法

将链表分为两半,翻转后一半,再将两个链表合并。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
private:
    ListNode* cutlist(ListNode* head){  //分割链表,返回后一半首地址
        if(!head || !head->next)
            return NULL;
        ListNode* slow=head;
        ListNode* fast=head->next;
        while(fast!=NULL && fast->next!=NULL){
            slow=slow->next;
            fast=fast->next->next;
        }
        ListNode* p=slow->next;
        slow->next=NULL;
        return p;
    }
    ListNode* reverseList(ListNode* head) { //翻转链表
        if(!head)
            return NULL;
        ListNode* p=NULL,*q=head;
        while(q){
            ListNode* tmp=q->next;
            q->next=p;
            p=q;
            q=tmp;
        }
        return p;
    }
public:
    void reorderList(ListNode* head) {
        ListNode* tail=cutlist(head);
        tail=reverseList(tail);
        ListNode* p=head;
        while(tail){
            ListNode* q=tail->next;
            tail->next=p->next; 
            p->next=tail;
            tail=q;
            p=p->next->next;       
        }
    }
};

方法二:转化为数组

class Solution {
public:
    void reorderList(ListNode* head) {
        if(!head)
            return;
        vector<ListNode*> arr;
        while(head){
            arr.push_back(head);
            head=head->next;
        }
        int i=0,j=arr.size()-1;
        while(i<j){
            arr[i]->next=arr[j];
            i++;
            if(i==j)
                break;
            arr[j]->next=arr[i];
            j--;
        }
        arr[i]->next=NULL;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值