c++ - 移动链表中的第一项以结束 C++

标签 c++ linked-list

我需要将链表中的第一项移动到链表的末尾。我的问题是我要进入无限循环。当我消除无限循环的原因时(tail -> link != NULL; 在 for 循环中),我遇到了段错误。因此,寻找有关如何使此代码正常工作的想法。

#include <iostream>
#include <string>
using namespace std;

struct Node
{
  string data;
  Node *link;
};

class Lilist
{
  public:
    Lilist() {head = NULL;}
    void add(string item);
    void show();
    void move_front_to_back();
    Node* search(string target);

  private:
    Node *head;
};

int main()
{
  Lilist L1, L2;
  string target;

  L1.add("Charlie"); //add puts a name at the end of the list
  L1.add("Lisa");
  L1.add("Drew");
  L1.add("Derrick");
  L1.add("AJ");
  L1.add("Bojian");

  cout << "Now showing list One:\n";
  L1.show(); // displays the list (This function displayed the list properly)
  cout << "\n";

  L1.move_front_to_back();
  L1.move_front_to_back();
  L1.show();
  cout << "\n";

  return(0);
}


void Lilist::add(string item)
{
  Node *temp;
  if(head == NULL)
  {
    head = new Node;
    head -> data = item;
    head -> link = NULL;
  }
  else
  {
    for(temp = head; temp -> link != NULL; temp = temp -> link)
        ;
    temp -> link = new Node;
    temp = temp -> link;
    temp -> data = item;
    temp -> link = NULL;
  }
}

void Lilist::show()
{
  for(Node *temp = head; temp != NULL; temp = temp -> link)
    std::cout << temp -> data << " ";
}

void Lilist::move_front_to_back()
{
  Node *temp;
  Node *tail;

  temp = head;

  for(tail = head; tail != NULL; tail = tail -> link)
    ;

  head = head -> link;
  tail -> link = temp;
  temp -> link = NULL;
}

最佳答案

问题在于您如何计算 tail。请注意这一点(为简洁起见省略了不相关的行):

for(tail = head; tail != NULL; tail = tail -> link)
  ;
tail -> link = temp;

请注意,for 循环只会在 tailNULL 时终止。然后,您取消引用 tail ...它是 null。

所以改变for循环条件:

for (tail = head; tail->link != NULL; tail = tail->link)
  ;

这将找到列表中的最后一个元素,而不是从末尾流出。

[Live example]

关于c++ - 移动链表中的第一项以结束 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28440137/

相关文章:

c - 对链接列表使用按引用传递

java - 将 ArrayList 转换为 LinkedList

algorithm - 为什么 Floyd 的循环查找算法对于某些指针增量速度会失败?

c++ - libstdc++ 是否符合 MISRA C++?

c++ - QtQuick 按键事件传播

c++ - 使用 Dijkstra 算法的最小生成树

java - LinkedList temp.next 和 temp?

java - 链接结构

c++ - RegExp 查找不以特定单词结尾的特定字符串

c# - 使用指向 C# 中的函数的指针作为参数调用 C++ 函数