head of linklist passed as argument having problems changing value of head node
Jan 17, 2014 at 4:09am UTC
I am attempting to change the value of the head node in my list. I thought due to having pointer defined in parameter list I could change the address value of head node. The argument passed is a struct I did not have to use & in argument list to denote address of struct to compiler. This may have something to do with my problem. I did not include all routines called by main program just the deleteNode routine im having problems with.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
bool deleteNode(struct node *head, struct node *delptr)
{
node *cur = head;
node *tempNextptr= cur;
using namespace std;
while (cur)
{
if (cur == delptr)
{
tempNextptr->next = delptr->next;
if (cur == head)
head = head->next;
delete cur;
return true ;
}
tempNextptr = cur;
cur = cur->next;
}
return false ;
}
int main()
{
using namespace std;
node *head = new node;
struct node *found;
bool remove;
initNode(head,10);
display(head);
addNode(head,20);
display(head);
addNode(head,30);
display(head);
found = searchNode(head,20);
cout<<"search node = " << found->data<< endl;
remove = deleteNode(head,head);
cout<<"head= " <<head<<endl;
// display(head);
if (remove)
cout<<"true" <<endl;
else
cout<<"false" <<endl;
cin.clear();
cin.ignore(255,'/n' );
cin.get();
return 0;
}
Jan 17, 2014 at 4:48am UTC
You can pass a reference to the pointer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <iostream>
using namespace std;
void swap(int *& pointer_ref0, int *& pointer_ref1)
{
int * temp = pointer_ref0;
pointer_ref0 = pointer_ref1;
pointer_ref1 = temp;
}
int main()
{
int x = 4;
int y = 6;
int * x_ptr = &x;
int * y_ptr = &y;
swap(x_ptr, y_ptr);
std::cout << x << " " << y << std::endl;
std::cout << *x_ptr << " " << *y_ptr << std::endl;
}
Topic archived. No new replies allowed.