66-Reorder List

  1. Reorder List My Submissions QuestionEditorial Solution
    Total Accepted: 64392 Total Submissions: 281830 Difficulty: Medium
    Given a singly linked list L: L0→L1→…→Ln-1→Ln,
    reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes’ values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

思路:
1.找到中点,前半部分最后一个点
a.找到后半部分第一个点
b.后半部分入栈
c.遍历前半部分,间隔性依次链接栈中节点

时间复杂度:
空间复杂度:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        int len=0;
        if(head==NULL||head->next==NULL)return;
        if(head->next->next==NULL)return;
        ListNode *p=head,*fir_end,*sec_beg;
        while(p){
            len++;
            p = p->next;
        }
        int mid=(len%2==0)?len/2:len/2+1;
        mid = mid -1;
        fir_end = head;
        while(mid--){
            fir_end=fir_end->next;
        }
        sec_beg = fir_end->next;
        stack<ListNode*> slist;
        while(sec_beg!=NULL){
            slist.push(sec_beg);
            sec_beg = sec_beg->next;
        }
        while(!slist.empty()){  //如果栈中有元素未被链接起来
            ListNode *tmp=head->next,*stop=slist.top(); //保存前半部分当前节点下一个节点
            head->next = stop;   //链接栈中元素
            stop->next = tmp;    //栈中元素链接到原来当前节点的下一元素,相当于在中间插入
            slist.pop(); 
            head = tmp;
        }
        if(head!=NULL)head->next = NULL;//如果链长为奇数,最后一个元素指向空
    }
};
posted @   Free_Open  阅读(221)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示