what I am trying to do is to modify simple linked list so far i have a functions to input a name, then output with reverse order, but i’m having trouble changing character at a specific location.
main code:
#include "list.h"
#include "string"
using namespace std;
int main(){
cout<<"What is your name \n";
string name;
getline(cin,name);
Node *list;
list = new_list();
for (int i=0; i<name.length();i++){
insert_front(&list,name[i]);
}
print_list(list);
int p;
char x;
cout<<"Change the position: ";
cin>>p;
cout<<"\n to the character " ;
cin>>x;
change_char(list, x, p);
print_list(list);
return 0;
}
and my list.cpp
#include "list.h"
Node* new_list(){
Node* list = 0;
return list;
}
void insert_front(Node** plist,char x){
Node* t;
t = new Node;
t->x = x;
t->next = *plist;
*plist = t;
return;
}
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( !is_empty(*plist) ){
t = (*plist)->next;
*plist = (*plist)->next;
delete t;
}
}
void delete_list(Node** plist){
while( !is_empty(*plist) )
delete_front(plist);
}
bool is_empty(Node* list){
return (list == 0);
}
void change_char(Node* plist, char x, int p){
Node* s;
s=(plist->next);
cout<<s<<endl;
cout<<plist<<endl;
return;
I’m stack on how to change character at a specific position. the change_char gives me back an address, but not a list, i’m not sure whats wrong.
Also how would the change in character be different from insertion and deletion of character.
Thanks for any help
Insertion = appending a char to the list; Deletion = removing a char from the list
I’d hope those would be obvious.
Changing at a position requires you walk the list to that position. You can do it iteratively or recursively, your choice. Assuming your positions are 1-based (as opposed to 0-based (and this code is NOT test compiled, so use at your own peril):