#include <iostream>
using namespace std;
struct ListNode{
char info;
ListNode * next;
ListNode(char newInfo, ListNode * newNext)
: info( newInfo ), next( newNext ){}
};
class String {
private:
ListNode* head;
public:
String( const char * s = "");
String( const String & s );
String& operator = ( const String & s );
~String();
int length(){
ListNode* current = head;
int i = 0;
while(current != NULL){
current = current->next;
i++;
}
return i;
}
char operator[](int i){
ListNode* current = head;
for(;i > 0; i--){
current = current->next;
}
return current->info;
}
};
ostream & operator << ( ostream & out, String& str );
istream & operator >> ( istream & in, String & str );
String::String( const char * s) {
if (s == "") {
head = NULL;
return;
}
ListNode* newNode = new ListNode(s[0], NULL);
head = newNode;
ListNode* current = head;
for (int i = 1; s[i] != 0; current = current->next) {
current->next = new ListNode(s[i], NULL);
++i;
}
}
String::String(const String& s ) {
ListNode* current = new ListNode((s.head)->info, NULL); //make all next's null just in case
head = current;
for(ListNode* sstart = s.head->next; sstart != NULL; sstart = sstart->next) {
current->next = new ListNode(sstart->info, NULL);
current = current->next;
}
}
String& String::operator = ( const String & s ) {
ListNode* start = head;
ListNode* tmp;
while(start != NULL) {
tmp = start->next;
delete start;
start = tmp;
}
head = NULL;
if (s.head == NULL)
return *this;
ListNode* current = new ListNode((s.head)->info, NULL); //make all next's null just in case
head = current;
for(ListNode* sstart = s.head->next; sstart != NULL; sstart = sstart->next) {
current->next = new ListNode(sstart->info, NULL);
current = current->next;
}
return *this;
}
String::~String() {
ListNode* nextNode = head;
ListNode* tmp;
while(nextNode) {
tmp = nextNode->next;
delete nextNode;
nextNode = tmp;
}
}
ostream & operator << ( ostream & out, String& str) {
for (int i = 0; i < str.length(); ++i) {
out << str[i];
}
return out;
}
istream & operator >> ( istream & in, String & str ) {
int len = in.gcount();
char* buf = new char[len];
char inChar;
for(int i = 0; in >> inChar; ++i) {
buf[i] = inChar;
}
String tmp(buf);
str = tmp;
}
int main(){
String s("Hello");
String t("Goodbye");
s = t;
cout<<s;
return 0;
}