Hi guys. For some reason I cannot get the linked list to print. I want to copy it(which works) but I cannot get the list to print after copying it. Any suggestions?

#include <iostream>
using namespace std;
struct node
{
	int info;
	node* next;
};

int main()
{
	node* list;
	list = new node;
	list->next = NULL;
	node* curr = list;
	list->info = 0;
	int num = 1;
	while(num <= 100)
	{
		node* temp = new node;
		if (temp == NULL)
		{
			cout << "Error. No memory was allocated.";
			break;
		}
		temp->info = num;
		curr->next = temp;
		curr = curr->next;
		num++;
	}
	curr = list;
	while(curr != NULL)//print linked list
	{
		cout << "node: " << curr->info;
		cout << endl;
		curr = curr->next;
	}

	cout << "Copying Linked List";
	//copy linked list
	while(curr != NULL)
	{
		node* copy = new node;
		copy->info = curr->info;
		copy->next = NULL;
		curr = curr->next;
	}
	cout << "The list was copied.";

	copy = curr;
	while(copy != NULL)//print copied linked list
	{
		cout << "node: " << copy->info;
		cout << endl;
		copy = copy->next;
	}

	return 0;
}

1) Program in C++ not C.

2) Second :

//copy linked list
	while(curr != NULL){...}
 //...

copy = curr

that exits only when curr is NULL right? So when you set copy = curr, you are setting
copy to NULL essentially. Thats why your last loop isn't getting executed.

PROGRAM IN C++ not C.

//copy linked list
	while(curr != NULL){	//Observation #1
          //...
	}
	cout << "The list was copied.";
 
	copy = curr; //Observation #2
	while(copy != NULL)//print copied linked list //Observation #3

You see what you did?

PROGRAM IN C++ not C.

//copy linked list
	while(curr != NULL){	//Observation #1
          //...
	}
	cout << "The list was copied.";
 
	copy = curr; //Observation #2
	while(copy != NULL)//print copied linked list //Observation #3

You see what you did?

It seems to me that your copy logic is not right.

//copy linked list
	while(curr != NULL)
	{
		node* copy = new node;
		copy->info = curr->info;
		copy->next = NULL;
		curr = curr->next;
	}
	cout << "The list was copied.";

Observations:
1. You do not have a pointer to point to the head of the list (this will lead to failure to iterate through the list later)
2. The code shown above merely allocate a node for each found in current list. Copy its info, then move on the next item in current list. The 'next' pointer of the new list is not linked up. After exiting the while loop, you will not have any way to access the 'copied' nodes. This will created a serious memory leak issue.

This article has been dead for over six months. Start a new discussion instead.