我的问题是我正在尝试根据用户输入在int h给出的特定位置插入一个字母到链表中。但是每次运行程序时,只有列表中的第二个字符发生变化无论用户输入程序的数量。
Example:
./h
Name: koala
a<-l<-a<-o<-k
Change the position: 2
To the character: 3
a<-l<-3<-o<-k
Insert the Character: F
To the Postion: 3
a<-F<-l<-3<-o<-k
我希望它看起来像。
./h
Name: koala
a<-l<-a<-o<-k
Change the position: 2
To the character: 3
a<-l<-3<-o<-k
Insert the Character: F
To the Postion: 3
a<-l<-3<-F<-o<-k
我知道我的问题出在我的lists.cpp的insert_char()函数中,但是我无法弄清楚我做错了什么......
List.h
#include <iostream>
using namespace std;
struct Node;
Node* new_list();
void insert_front(Node** plist,char x);
void insert_char(Node* plist, char x, int p);
void change_char(Node* plist, char x, int p);
void print_list(Node* list);
void delete_front(Node** plist);
void delete_list(Node** plist);
//void delete_char(Node* plist,int p);
struct Node {
char x;
Node *next;
};
的main.cpp
struct Node {
char x;
Node *next;
};
int main(){
Node *list;
list = new_list(); //new empty list
cout<<"Name: ";
string name;
cin>> name;
for (int i =0; i < name.length(); i++)
insert_front(&list, name[i]);
//---------print list-------------------------
print_list(list);
cout <<"Change the position: ";
int z;
cin>> z;
cout<< "To the character: " ;
char x;
cin>> x;
change_char(list, x, z);
print_list(list);
cout <<"Insert the Character: ";
char y;
cin>> y;
cout<< "To the Postion: ";
int h;
cin>> h;
insert_char(list, y, h);
print_list(list);
return 0;
}
lists.cpp
Node* new_list()
{
Node* list = 0; //in C++ it is better to use 0 than NULL
return list;
}
void insert_front(Node** plist,char x){
Node* t;
t = new Node;
t->x = x;
t->next = *plist;
*plist = t;
return;
}
void change_char(Node* plist, char x, int p)
{
Node* s = plist;
for (int i=1; i<p && 0!=s;i++)
s = s->next;
if (0 != s)
s->x = x;
return;
}
void insert_char(Node* plist, char x, int p){
Node* s = plist;
Node* a = new Node();
for (int i=1; i<p && s; i++)
a->next=s->next;
s->next=a;
if (0 !=s)
a->x=x;
return;
}
//void delete_char(Node* plist,int p)
void print_list(Node* list){
Node* p;
p = list;
if(p == 0)
cout << "--- empty list ---" << endl;
while(p !=0){
cout << p->x<<"<-";
p = p->next;
}
cout << endl;
}
void delete_front(Node** plist){
Node* t;
if( *plist != 0){ // list is not empty
t = (*plist);
*plist = (*plist)->next;
delete t;
}
}
void delete_list(Node** plist){
while(*plist != 0) //while list not empty
delete_front(plist);
}
bool is_empty(Node* list){
return (list == 0);
}
答案 0 :(得分:1)
insert_char
中的for循环只是一遍又一遍地“插入”字符。我认为您的意思是将s
提升到插入的起点(由h
确定)。
<强>更新强>
这部分是错误的,原因如下:
for (int i=1; i<p && s; i++)
a->next=s->next;
s->next=a;
请注意,缩进会产生误导。由于您没有大括号,因此只有中间线是循环的一部分。实际上,你写了:
for (int i=1; i<p && s; i++) {
a->next=s->next;
}
s->next=a;
就个人而言,我总是在块上使用大括号,即使它们只包含一个语句。
所以你多次设置a->next
而不是前进到你想去的列表中。
您需要前进到循环中想要新元素的位置,然后进行实际插入。
// Advance s to index p.
for (int i = 1; i < p && s->next; i++) {
s = s->next;
}
// Insert a at s.
a->next = s->next;
s->next = a;