2011-11-28 21:38:52

I have a list of data in a program that I'm writing. I need to copy the data from one list to another. I'm going to delete the first list after I copied it, so copying the the pointers would not be what I'm looking to do. If it was, I would use the = to do this. The list is a circular single dumby headed linked list. Did I say it was in C++? Any good Ideas on how to do this? Some exsamples would be nice, but that may lose people...

All that is gold does not glitter, Not all those who wander are lost; The old that is strong does not wither, Deep roots are not reached by the frost. From the ashes a fire shall be woken, A light from the shadows shall spring; Renewed shall be blade that was broken, The crownless again shall be king.
DropBox Referral

2011-12-03 20:50:49

Hi,
If you want to copy stuff from one linked list to another, you can do it manually by reallocating the list. I've written some code below but it was done quickly, I hope this points you in the right direction and let me know if you have any questions. I'm not sure if it will compile (it's mostly to be taken as pseudocode) but it should give you an idea. Good luck!
struct listItem {
struct listItem* next; //next listItem in linked list
int value; //value
};
void copyList(struct listItem*, struct listItem*);
void copyList(struct listItem* firstList, struct listItem* destList)
{
struct* copyingItem = firstList; //caller may want to do stuff with the first list.
struct list* copyTo = destList; //so we don't lose the pointer to the beginning of the new list
while (copyingItem != NULL) { //makes sure we don't copy a null list
copyTo->value = copyingItem->value;
if (copyingItem->next != NULL) {
copyTo->next = (struct listItem*)malloc(sizeof(struct listItem));
copyTo = copyTo->next;
} // If there's still a next item
copyingItem = copyingItem->next;
} //while
}

2011-12-03 20:56:27

Sorry, I just reread your post and you have a circular list. What you could do is modify the listItem structure to contain a value, int copied = 0;. Then, before you copy the item, check this value. If it's 1 you've copied it, so you're at the beginning of the list. You'll also have to maintain a pointer to the start of the list (destList in my example) and make sure you don't lose it. So once you're done copying just point the last node->next back to destList. You'll also have to set previous pointers as well if you're looking for a doubly-circular-linked list but I'm assuming you're only going one way, so just the next pointer will be sufficient.

2011-12-04 23:52:22

Thanks a bunch.

All that is gold does not glitter, Not all those who wander are lost; The old that is strong does not wither, Deep roots are not reached by the frost. From the ashes a fire shall be woken, A light from the shadows shall spring; Renewed shall be blade that was broken, The crownless again shall be king.
DropBox Referral