leetcode笔记—Reorder List

给一个链表  L L 0 L 1 →…→ L n-1 L n ,

需要返回: L0LnL1Ln-1L2Ln-2→…

思路1:

void reorderList(ListNode* head) {
       ListNode* p=head;
        while(p&&p->next)
        {
            ListNode* pnext=p->next;   //记下下一个节点
            ListNode* temp=p;
            if(p->next->next==NULL)
            {
                p=p->next;
            }
            else
            {
                while(temp->next&&temp->next->next)
                {
                    temp=temp->next;
                    
                }//让temp指向倒数第二个节点
                p->next=temp->next;  //指向最后一个节点
                temp->next=NULL;    //删除最后一个节点
                p=p->next;          //连接后面的节点
                p->next=pnext;
                p=p->next;
         
            }
        }
        if(p)
        {
            p->next=NULL;
     }}
思路2: 
 

if(head == NULL){  
            return;  
        }  
          
        ListNode* p1 = head;  
        ListNode* p2 = splitList(head);  
          
        p2 = revertList(p2);  
          
        mergeList(p1, p2);  
    }  
      
    void mergeList(ListNode * p1, ListNode * p2){  //合并链表
        while(p2 != NULL){  
            ListNode* tmp = p2;  
            p2 = p2->next;  
              
            tmp->next = p1->next;  
            p1->next = tmp;  
            p1 = p1->next;  
            p1 = p1->next;  
        };  
    }  
      
    ListNode* splitList(ListNode *head){  //去后半部分链表
        ListNode* slow = new ListNode(0);  
        slow->next = head;  
        ListNode* fast = slow;  
          
        while(fast->next != NULL && fast->next->next != NULL){  
            slow = slow->next;  
            fast = fast->next;  
            fast = fast->next;  
        }  
          
        if(fast->next != NULL){  
            slow = slow->next;  
            fast = fast->next;  
        }  
          
        ListNode* tmp = slow->next;  
        slow->next = NULL;  
        return tmp;  
    }  
      
    ListNode* revertList(ListNode* head){  //翻转链表
        if(head == NULL){  
            return NULL;  
        }  
          
        ListNode* p = head->next;  
        head->next = NULL;  
          
        while(p != NULL){  
            ListNode* tmp = p;  
            p = p->next;  
            tmp->next = head;  
            head = tmp;  
        }  
        return head;  
    }


 
 

你可能感兴趣的:(leetcode笔记—Reorder List)