0

Hello, I usually don't complain too much. But this time I am getting mad. I just wrote a linked list, where
1. If the value was not present before in the list, it will be added. In this case, there is a capacity. If the new value increases the list size more than capacity, then the eldest one will be deleted.
2. If the value was present in the list, it will be added on the top of the list, and the old value have to be removed.

I am done with all of the parts, but I can't remove the old value.... my code goes below:

void RList::add(int newNum) {
	lNode *h, *t, *p=NULL, *c;
	bool run=false;;

	if(!numberExists(newNum)) {
		if(!(size<capacity)) {
			throw invalid_argument ("RedialList::add() Not enough place");
		}
		size++;
	}
	else run=true;
	if(head==NULL) {
		h=new lNode(newNum, NULL);
		head=h;
		return;
	}

	h= new lNode(newNum, head);
	head=h;
	if(numberExists(newNum) && run) {
		c=head;
		for(p=head->next;;p=p->next;) {
			if(p->phnNo==newNum){
				c=p->next;
				delete c;
				return;
			}
		}
	}
}

so far i can see, the problem is in this code:

if(numberExists(newNum) && run) {
		c=head;
		for(p=head->next;;p=p->next;) {
			if(p->phnNo==newNum){
				c=p->next;
				delete c;
				return;
			}
		}
	}
2
Contributors
1
Reply
2
Views
10 Years
Discussion Span
Last Post by Lerner
0

1) What's the terminating condition of the for loop?

2) If I have APA and I want to remove the first A then I can store the head in a temp node, change head to to head->next, then delete the temp node.

However, if I have APCP and I want to remove the first P toget ACP I have to disconnect the first P from C and connect the A to the C without changing head and then I can delete P. In theory, if I use a searching node called current, then if current->next->value == P, then current->next can be assigned to a temp node, current->next->next can be assigned to current->next , temp node->next can be nulled and then temp node can be deleted. With any luck it might work. Alternatively, I could keep track of current node and prior node where current node is same as prior node next, as long as the list is longer than a single node. Then current node->next can be assigned to prior node->next and current node can be deleted. That should work, too. Good luck.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.