• [LeetCode] Reorder List


    Given a singly linked list LL0L1→…→Ln-1Ln,
    reorder it to: L0LnL1Ln-1L2Ln-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}.

    Solution:

    /**
     * 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) {
          if(head == NULL || head -> next == NULL) 
            return;
          ListNode *fast = head, *slow = head, *tmp1 = NULL, *tmp2 = NULL, *ansHead = NULL, *ansEnd = NULL;
            while(fast -> next != NULL)
          {
            fast = fast -> next;
            if(fast -> next == NULL)
            {
              //reach the end
              break;
            }
            else
            {
              fast = fast -> next;
              slow = slow -> next;
            }
          } 
            
          ListNode *list2start = slow -> next;
          slow -> next = NULL;
          tmp1 = list2start -> next;
          list2start -> next = NULL;
          while(tmp1 != NULL)
          {
            tmp2 = tmp1 -> next;
            tmp1 -> next = list2start;
            list2start = tmp1;
            tmp1 = tmp2;
          }
          tmp1 = head -> next;
          tmp2 = list2start;
          ansHead = head;
          ansEnd = head;
          while(tmp1 != NULL || tmp2 != NULL)
          {
            if(tmp2 != NULL)
            {
              ansEnd -> next = tmp2;
              tmp2 = tmp2 -> next;
              ansEnd = ansEnd -> next;
            }
            if(tmp1 != NULL)
            {
              ansEnd -> next = tmp1;
              tmp1 = tmp1 ->next;
              ansEnd = ansEnd -> next;
            }
          }
          head = ansHead;
          return;
        }
    };
  • 相关阅读:
    【HTML】input标签中alt属性和title属性的比较
    【HTML】WWW简介
    【MySQL】MySQL的常规操作
    iOS编程(双语版)
    Swift语言精要
    Swift语言精要
    python网络爬虫
    Python小任务
    如何在onCreate方法中获取视图的宽度和高度
    python网络爬虫
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3673203.html
Copyright © 2020-2023  润新知