C++ 单链表交换函数(int,int)

C++ 单链表交换函数(int,int),c++,visual-studio-2013,int,swap,singly-linked-list,C++,Visual Studio 2013,Int,Swap,Singly Linked List,我认为我的问题在于push_backs()的用法,但是我想不出一个简单的方法来解决这个问题。我需要它在参数中给出的两个整数处交换节点,我感谢任何帮助!我是一名大学一年级新生,在当今的世界上闯出了一条路,我愿意接受反馈 void MyList::swap(int i, int j) { if (i == j || i > size() || j > size()) return; Node *temp = head; delete head; //pretty su

我认为我的问题在于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;
   }
}

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

您可以交换第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;
}

是的,
delete head
将导致以后取消引用
head
时出现错误。为什么要释放头部节点的内存?特别是当你以后要使用它的时候?因为MyList是由“head”定义的,我不能把东西添加到完整的列表中,正如我所看到的。哈哈,你应该在上读这篇文章。交换值只适用于这个例子。如果
节点
的实现发生了变化(违反了打开/关闭原则),它就需要更改。非常好,除了最后的一个非常小的错误,它工作得非常好,我从来没有想过要这样做!非常感谢你!啊,是的。很高兴我能帮忙。
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;
}