2 Replies - 667 Views - Last Post: 20 February 2013 - 05:08 AM Rate Topic: -----

#1 masteringthebasics  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 19-February 13

Linked List of chars from string

Posted 19 February 2013 - 11:53 PM

I'm given a task where I should assign a string to a linked list of chars.
My idea to solve this problem is by creating s.length() of nodes, setting their value by a for loop and setting their next to NULL. Then by creating all the nodes, I can proceed to connecting them each other, but the last code
head = NodeArray[0] doesn't work for me. I think I have a misunderstanding somewhere. Suggestions greatly appreciated. Thank you

for class StringADT
class StringADT{

	private:
		struct Node {
			char data;
			Node* next;
		};
		Node* head;

	public:
		StringADT()
		{ head = NULL; }

		void append(string); //10

		void display() const; //13

		~StringADT(); //3



for the member functions
void StringADT::append(string s)
{ 
	Node* NodePtr;
	Node* newNode;

	int slength = s.length();

	Node *NodeArray = new Node[slength];

	for (unsigned i = 0; i < s.length(); i++)
	{
		NodeArray[i].data = s.at(i);
		NodeArray[i].next = NULL;
	}
	
	//NOHEAD
	if (!head)
	{
		head = NodeArray[0]; //DOESN'T WORK.

	}
}



Is This A Good Question/Topic? 0
  • +

Replies To: Linked List of chars from string

#2 masteringthebasics  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 19-February 13

Re: Linked List of chars from string

Posted 20 February 2013 - 12:32 AM

Nevermind I actually had it working by assigning with this syntax.
for (unsigned x = 0; x <= s.length(); x++)
{
head = (NodeArray + x);
}


why can't this:
head = NodeArray[0];


work?
Was This Post Helpful? 0
  • +
  • -

#3 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5882
  • View blog
  • Posts: 12,761
  • Joined: 16-October 07

Re: Linked List of chars from string

Posted 20 February 2013 - 05:08 AM

Node *NodeArray = new Node[slength];



Stop. Right there. Why? You are doing a linked list. What is the point of this?


I want you to add another method to your StringADT. It's void append(char);. You want to append a char at a time, don't you?

I'll rewrite your void append(string); for you:
void StringADT::append(string s) { 
	for (unsigned i = 0; i < s.length(); i++) {
		append(s.at(i));
	}
}



Now, forget std::string and concentrate on your real problem, adding a single character.

This post has been edited by baavgai: 20 February 2013 - 05:08 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1