Data Structures Exam Review

Reviewing for Data Structures Test.

Page 1 of 1

3 Replies - 4911 Views - Last Post: 28 March 2009 - 05:53 PM Rate Topic: -----

#1 Zerobu  Icon User is offline

  • Black Hatter

Reputation: 13
  • View blog
  • Posts: 1,822
  • Joined: 14-January 08

Data Structures Exam Review

Post icon  Posted 28 March 2009 - 03:55 PM

Hello everyone, I am reviewing for a Data Structures test that i am taking on Monday, I thought i might need some help on some questions. It will cover Linked Lists, Stacks, and Queues.

My first question is this:
I want to ask the user to input a list of numbers in a program. The program will keep asking for numbers as long as zero isn't entered. After its done asking for numbers, I want the program to output the numbers that should be in the list. I am implementing this with a linked list.

Here is my code
#include <iostream>
#include <cstddef>
using namespace std;

struct node
{
	int data;
	node* next;
};

void main ()
{
	int num = 0;
	node *x = new node;

	do
	{

	cout <<"Enter a number ";
	cin >> num;

	x ->data = num;
	x ->next = NULL;

	}while(num != 0);

	

	for(node*curr = x; curr != NULL; curr= curr->next)  //Traverse the list and outputs each number
	{
		cout << curr->data;
	}

	
}


I know the problem lies somewhere around here:
 

	x ->data = num;
	x ->next = NULL;



It only seems to output the zero it should traverse the list and output the contents in the list.
For some reason only zero seems to be in the list.

This post has been edited by Steffan: 28 March 2009 - 04:04 PM


Is This A Good Question/Topic? 1
  • +

Replies To: Data Structures Exam Review

#2 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Data Structures Exam Review

Posted 28 March 2009 - 04:21 PM

you have to allocate a new node for each number, and you have to delete them when you are done.

So it helps to have a Node *Head = x for the first one... this way you can do something like:
Node * ptr; while (ptr-next != NULL) { delete ptr; }
Was This Post Helpful? 1
  • +
  • -

#3 Zerobu  Icon User is offline

  • Black Hatter

Reputation: 13
  • View blog
  • Posts: 1,822
  • Joined: 14-January 08

Re: Data Structures Exam Review

Posted 28 March 2009 - 05:06 PM

So do i start off by saying head = ptr before i go into the do while loop?

I got it thanks.

This post has been edited by Steffan: 28 March 2009 - 05:14 PM

Was This Post Helpful? 0
  • +
  • -

#4 Zerobu  Icon User is offline

  • Black Hatter

Reputation: 13
  • View blog
  • Posts: 1,822
  • Joined: 14-January 08

Re: Data Structures Exam Review

Posted 28 March 2009 - 05:53 PM

Ok i have another question this time it deals with Stacks, and the Maze problem.

Click Here to see the problem

Whats the best way, (using stacks to this)?

This post has been edited by Steffan: 28 March 2009 - 05:56 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1