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;//如果链长为奇数,最后一个元素指向空
        }
    };
  • 相关阅读:
    LoadRunner脚本增强技巧之参数化(二)
    LoadRunner脚本增强技巧之参数化(一)
    LoadRunner脚本增强技巧之手动关联
    LoadRunner脚本增强技巧之自动关联
    LoadRunner录制用户操作
    Fiddler绕过前端直接和后台进行交互
    Android手机Fiddler真机抓包
    zabbix自定义监控项二
    zabbix自定义监控项一
    zabbix主机自动发现和监控
  • 原文地址:https://www.cnblogs.com/freeopen/p/5482889.html
Copyright © 2011-2022 走看看