我的问题是我试图根据用户在 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
我知道我的问题出在我的 list.cpp 中的 insert_char() 函数中,但就是不知道我做错了什么......
列表.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;
};
主文件
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;
}
列表.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);
}