我需要將鏈表中的第一項移動到列表的末尾。我的問題是我會陷入無限循環。當我刪除無限循環的原因(tail -> link != NULL
;在for循環中)時,我得到一個seg故障。因此,尋找關於如何讓這些代碼正常工作的想法。將鏈表中的第一項移到結尾C++
#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;
}
郵報[MCVE](http://stackoverflow.com/help/mcve)。當你開始時,列表是否已經損壞? – Angew 2015-02-10 19:29:15
目前我無法輸入所有內容,但我知道列表並未損壞。這是該計劃的後半部分。前半部分添加6個節點,然後輸出列表。我不記得我在這個部分中的代碼,但我曾經在某個地方「刪除」它移動的節點@Angew – transmini 2015-02-10 19:32:18
如果您沒有必要的信息,那麼無法幫助您沒有理由在這裏保留這個問題。只是爲了記錄:這聞起來也像功課。 – 2015-02-10 19:33:52