zoukankan      html  css  js  c++  java
  • 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;//如果链长为奇数,最后一个元素指向空
        }
    };
  • 相关阅读:
    perl6检测网站CMS脚本(测试代码)
    perl6 struct2-045 EXP
    perl6 单线程破解phpmyadmin脚本
    perl6 登录phpmyadmin
    PHP反序列化漏洞学习
    PHP对象5: define / const /static
    PHP对象4: final 不允许重写方法或不允许继承类
    ISCC之misc复现-High起来!
    宁波市第二届CTF之cripto1
    宁波市第二届CTF部分WP之msc1,msc2
  • 原文地址:https://www.cnblogs.com/freeopen/p/5482889.html
Copyright © 2011-2022 走看看