【问题标题】:Singly Linked List swap function (int, int)单链表交换函数 (int, int)
【发布时间】:2015-01-16 20:57:00
【问题描述】:

我认为我的问题在于 push_backs() 的使用,但我想不出解决这个问题的简单方法。我需要它来交换争论中给出的两个整数的节点,我感谢任何帮助!我是一名大一新生,在当今世界上崭露头角,乐于接受反馈!

void MyList::swap(int i, int j)
{
   if (i == j || i > size() || j > size()) return;

   Node *temp = head;
   delete head; //pretty sure this is what's giving me issues as well

   for (unsigned x = 0; x < size(); x++)
   {

      if (x == i)
      {
         int y = 0;
         for (Node *itt = head; itt; itt = itt->next)
         {
            if (y == j)
               push_back(itt->value);
            y++;
         }
      }
      else if (x == j)
      {
         int y = 0;
         for (Node *itt = head; itt; itt = itt->next)
         {
            if (y == i)
               push_back(itt->value);
            y++;
         }
      }
      else
      {
         push_back(temp->value);
      }

      temp = temp->next;
   }
}

供参考,这里是Node类

  using namespace std;
  class Node
  {
   public:
        char value;
        Node *next;
        Node(char value)
        :value(value), next(0)
    {}
   };

【问题讨论】:

  • 是的,当您稍后取消引用 head 时,delete head 将导致 undefined behavior。为什么要释放头节点的内存?尤其是以后要使用的时候?
  • 因为 MyList 是由“head”定义的,我无法将内容添加到完整列表中,正如我所见。哈哈
  • 你应该在debugging your small program阅读这篇文章。

标签: c++ visual-studio-2013 int swap singly-linked-list


【解决方案1】:

您可以交换第 i 个和第 j 个节点的值。

void MyList::swap(int i, int j){
  if(head == NULL) return;

  // Get ith node
  node* node_i = head;
  int node_cnt = 0;
  while(1){
    if(node_cnt == i) break;  
    if(node_i == NULL) return; 
    node_i = node_i->next;
    node_cnt++;
  } 

  // Get jth node
  node* node_j = head;
  node_cnt = 0;
  while(1){
    if(node_cnt == j) break;  
    if(node_j == NULL) return; 
    node_j = node_j->next;
    node_cnt++;
  }

  // Swap values of nodes
  int temp = node_i->value;
  node_i->value = node_j->value;
  node_j->value = temp;
}

【讨论】:

  • 交换值仅适用于本示例。如果Node的实现发生变化(违反Open/Closed原则),则需要更改。
  • 非常好,除了最后的一个很小的错误,它的效果非常好,我从来没有想过这样做!非常感谢!
  • 啊,是的。很高兴我能帮上忙。
【解决方案2】:

我认为有比你更好的方法。你真的不需要delete 任何东西。您只需要获取指向第 i 个节点(如果有)之前的节点的指针和指向第 j 个节点(如果有)之前的节点的指针。然后进行交换。

【讨论】:

    猜你喜欢
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多