【问题标题】:Efficiently swap elements pairwise in a singly linked list在单链表中有效地成对交换元素
【发布时间】:2014-01-21 00:42:12
【问题描述】:

我用 C++ 编写了一个函数,可以很好地在单链表中成对交换元素。但是,我想知道是否有更有效的方法来做同样的事情。具体来说,我编写的函数有一个案例,它处理链表中只有两个元素的情况。我想知道这种情况是否可以省略并放在一般情况下。我尝试这样做,但未能获得输出。是否可以?这是我的代码 sn-p...

struct Node* swap(struct Node* head){
  struct Node* temp = NULL;
  struct Node* cur;
  struct Node* next;

  cur = head;
  next = cur->next;

  // Empty list.
  if(head == NULL){
    cout<<"List is empty. \n";
    return NULL;
  }

  // Only one element in the list.
  if(next == NULL){
    return cur;
  }

  // If two elements in the list.
  else if(next->next == NULL){
    cur->next = NULL;
    next->next = cur;
    return next;
  }

  // General case.
  else{
    head = next;
    while(cur!=NULL){

      if(next == NULL)
        break;

      if(next->next == NULL)
        break;      

      cur->next = next->next;
      next->next = cur;


      if(temp == NULL)
        temp = cur;

      else{
        temp->next = next;
        temp = cur;
       }    

       cur = cur->next;
       next = cur->next;


     }
    return head;
    }
 }

【问题讨论】:

    标签: c++ singly-linked-list


    【解决方案1】:

    是的,您可以在一般情况下包含二元情况、一元情况和零元情况。循环可以开始于

    while(cur != NULL && cur->next != NULL)
    

    【讨论】:

      【解决方案2】:

      除非我遗漏了什么,否则 Beta 的解决方案似乎应该做到这一点。

      另外,不是答案,而是打扰我:

      if(temp == NULL){
          temp = cur;
      }
      else{
          temp->next = next;
          temp = cur;
      }   
      

      如果 temp 最终以 cur 结尾,您可以将其压缩成

      if(temp != NULL){
          temp->next = next;
      }
      temp = cur;
      

      【讨论】:

        猜你喜欢
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多