C++ 中的列表重排


假设我们有一个像 l1 -> l2 -> l3 -> l4 -> … -> l(n-1) -> ln 这样的链表。我们需要将此列表重新排列为 l1 -> ln -> l2 -> l(n - 1) -> … 等等的形式。这里的约束条件是,我们不能修改列表节点中的值,只能更改节点本身。例如,如果列表为 [1,2,3,4,5],则输出将为 [1,5,2,4,3]

为了解决这个问题,我们将遵循以下步骤 -

  • 定义一个名为 reverse 的方法来执行反转操作。这将采用节点 head 和节点 prev。这将如下所示 -

  • 如果 head 为空,则返回 prev

  • temp := head 的下一个节点

  • head 的下一个节点 := prev,prev := head

  • 返回 reverse(temp, prev)

  • 重排序任务将如下所示 -

  • 如果 head 为空,则返回 null

  • 定义两个节点指针,称为 slow 和 fast,并用 head 初始化它们

  • 当 fast 和 fast 的下一个节点都不为空时,

    • slow := slow 的下一个节点

    • fast := fast 的下一个节点的下一个节点

  • fast := reverse(slow 的下一个节点)

  • 将 slow 的下一个节点设置为 null,slow := head

  • 定义两个列表节点指针 temp1 和 temp2

  • 当 fast 不为空时

    • temp1 := slow 的下一个节点,temp2 := fast 的下一个节点

    • slow 的下一个节点 := fast,fast 的下一个节点 := temp1

    • slow := temp1,fast := temp2

让我们看看以下实现,以便更好地理解 -

示例

 在线演示

#include <bits/stdc++.h>
using namespace std;
class ListNode{
   public:
   int val;
   ListNode *next;
   ListNode(int data){
      val = data;
      next = NULL;
   }
};
ListNode *make_list(vector<int> v){
   ListNode *head = new ListNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      ListNode *ptr = head;
      while(ptr->next != NULL){
         ptr = ptr->next;
      }
      ptr->next = new ListNode(v[i]);
   }
   return head;
}
void print_list(ListNode *head){
   ListNode *ptr = head;
   cout << "[";
   while(ptr){
      cout << ptr->val << ", ";
      ptr = ptr->next;
   }
   cout << "]" << endl;
}
class Solution {
   public:
   ListNode* successor = NULL;
   ListNode* reverse(ListNode* head, ListNode* prev = NULL){
      if(!head)return prev;
      ListNode* temp = head->next;
      head->next = prev;
      prev = head;
      return reverse(temp, prev);
   }
   void reorderList(ListNode* head) {
      if(!head)return;
      ListNode* slow = head;
      ListNode* fast = head;
      while(fast && fast->next){
         slow = slow->next;
         fast = fast->next->next;
      }
      fast = reverse(slow->next);
      slow->next = NULL;
      slow = head;
      ListNode *temp1, *temp2;
      while(fast){
         temp1 = slow->next;
         temp2 = fast->next;
         slow->next = fast;
         fast->next = temp1;
         slow = temp1;
         fast = temp2;
      }
   }
};
main(){
   vector<int> v = {1,2,3,4,5};
   ListNode *h1 = make_list(v);
   Solution ob;
   (ob.reorderList(h1));
   print_list(h1);
}

输入

[1,2,3,4,5]

输出

[1, 5, 2, 4, 3, ]

更新于: 2020-04-30

783 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.