-
need help , plzz
hi all,
i am having kinda difficulty with pointers in C.
if i have a program where i would have a linked list and each node contains some specific info. for example, i want to get 3 consecutive nodes, which would have LOADC, LOADC and ADD , respectively in each node, so first to find them. i would do
instruction * instr, *temp; <-- instr is already pointing to the list.
temp = insr ; <-- temp will travers thru the list
while (temp!=null){
if(temp->opcode == LOADC){ //opcode is fieldtype in the code
int x = field 1;
temp = temp->next;
if(temp->opcode ==LOADC) //2ndnode
int y = field1;
temp = temp->next;
if(temp->opcode == ADD)//3rd node
int z = x + y;
}
temp = temp->next;
}
but i dont know how would i delete the 2nd and 3rd node and set the pointer back at the first node.
i would really appreciate it if someone would help me out with this.
thanks a lot again.
-
the easiest way to deal with this might be to keep a spare node pointer to the first node, or instead of moving the node pointer for each comparison just using another ->next... temp->next->opcode, temp->next->next->opcode... etc. when it comes time to delete the nodes, just set the spare pointer to temp->next->next->next (or what you like), then free the nodes beforehand in reverse order (temp->next->next, temp->next, temp).
while i can't see all the code you have written so far, for the example given i have a design suggestion. instead of testing for an entire series of nodes, you might want to just do a single operation for each node. for what you've given here, LOADC could push field1 onto a stack, and ADD could pop two numbers from the same stack and add them up.