hey all,
there I was, thinking I have linked list pretty much figured out, and here I am now; confused with a very simple problem (i think). Anyways, below is a code, where I am trying to create two seperate linked lists, abd later print them out. If I do just one, everything works fine, but when I do two, I get everything twice, basically instead of getting 0 1 2 3 4 I get 0 1 2 3 4 0 1 2 3 4.
any suggestions?
axon
Code:#include <iostream> using namespace std; struct Node { Node *pNext; Node *pPrev; int nData; }; Node *pHead, *pTail; void AppendNode( Node *pNode); //appends node to end of list void InsetNode(Node *pNode, Node *pAfter); //insert node into the list after pAfter void RemoveNode(Node *pNode); //Remove specified node from list void DeleteAllNodes(); //Delete the entire list int main() { Node *L1; Node *L2; //add items to linked list for ( int i = 0; i< 5; i++ ) { L1 = new Node; L1->nData = i; AppendNode( L1 ); } for ( i = 0; i< 5; i++ ) { L2 = new Node; L2->nData = i; AppendNode( L2 ); } //display all nodes cout << "-----------==LIST 1==--------------" << endl << endl; for ( L1 = pHead; L1 != NULL; L1 = L1->pNext ) { cout << L1->nData << endl; } cout << "-----------==LIST 2==--------------" << endl << endl; for ( L2 = pHead; L2 != NULL; L2 = L2->pNext ) { cout << L2->nData << endl; } return 0; } //======================================== void AppendNode( Node *pNode) { if ( pHead == NULL ) { pHead = pNode; pNode->pPrev = NULL; } else { pTail->pNext = pNode; pNode->pPrev = pTail; } pTail = pNode; pNode->pNext = NULL; } //======================================== void InsetNode(Node *pNode, Node *pAfter) { pNode->pNext = pAfter->pNext; pNode->pPrev = pAfter; if ( pAfter->pNext != NULL ) { pAfter->pNext->pPrev = pNode; } else { pTail = pNode; } pAfter->pNext = pNode; } //======================================== void RemoveNode(Node *pNode) { if ( pNode->pPrev == NULL ) { pHead = pNode->pNext; } else { pNode->pPrev->pNext = pNode->pNext; } if ( pNode->pNext == NULL ) { pTail = pNode->pPrev; } else { pNode->pNext->pPrev = pNode->pPrev; } } //======================================== void DeleteAllNodes() { while ( pHead != NULL ) { RemoveNode( pHead ); } }