The problem is you are storing in every node the address of
str
as data (and you are overwriting the
str
content).
You may solve such a problem making a copy of the passed str content or, better, using std::string objects:
#include <iostream>
using namespace std;
struct Node{
Node *next;
string data;
};
void initNode(struct Node *head, const string & n){
head->next = NULL;
head->data = n;
}
void addNode(struct Node *head, const string & n){
Node *newNode = new Node;
newNode->data = n;
newNode->next = NULL;
Node *cur = head;
while(cur){
if(cur->next == NULL){
cur->next = newNode;
return;
}
cur = cur->next;
}
}
void display(struct Node *head){
Node *list = head;
while(list != NULL){
cout << list->data <<endl;
list = list->next;
}
}
int main(){
string str;
cout << "Enter 1st: ";
cin >> str;
Node *head = new Node;
initNode(head, str);
cout << "Enter 2nd: ";
cin >> str;
addNode(head, str);
cout << "Enter 3th: ";
cin >> str;
addNode(head, str);
cout << endl << "Show all value of linked list: " << endl;
display(head);
}
[update]
Quote:
but i want use char not string, what must I do?
Since you are using
C++
, you shouldn't use
C
-like strings, anyway...
#include <iostream>
#include <cstring>
using namespace std;
struct Node{
Node *next;
char *data;
};
void initNode(struct Node *head, const char * data){
head->next = NULL;
head->data = new char[strlen(data)+1];
strcpy(head->data, data);
}
void addNode(struct Node *head, const char * data){
Node *newNode = new Node;
newNode->data = new char[strlen(data)+1];
strcpy(newNode->data, data);
newNode->next = NULL;
Node *cur = head;
while(cur){
if(cur->next == NULL){
cur->next = newNode;
return;
}
cur = cur->next;
}
}
void display(struct Node *head){
Node *list = head;
while(list != NULL){
cout << list->data <<endl;
list = list->next;
}
in main()
{
char str[30];
cout << "Enter 1st: ";
cin.getline(str, 30);
Node *head = new Node;
initNode(head, str);
cout << "Enter 2nd: ";
cin.getline(str, 30);
addNode(head, str);
cout << "Enter 3th: ";
cin.getline(str, 30);
addNode(head, str);
cout << endl << "Show all value of linked list: " << endl;
display(head);
}
Please note:
- The above is ugly C++ code.
- You must perform cleanup, that is eventually pair every
new
call with the corresponding delete
. [/update]