linked list debugging (delete C++ keyword is mysterious)? -
i trying solve problem: delete node singly linked list give pointer node. approach overwrite data of next element in list onto current element of list.
in code below, have 2 versions of deleting code: deletenode , deletenode2.
void deletenode(node * x) { while(x->next != null){ x->data = x->next->data; x = x->next; } delete x; x=null; } void deletenode2(node * x) { while(x->next->next != null){ x->data = x->next->data; x = x->next; } x->data = x->next->data; delete x->next; x->next=null; } i initialized list with: 1,2,3,4,5 , tried delete node 3. deletenode output is: 1,2,4,5,0 while deletenode2: 1,2,4,5
also when remove "x->next=null" line deletenode2 has same output 1. question is, how delete statement work in c++? set bits in pointed address 0?
for deletenode(..), x pointer has been deleted not appropriately been set null because prints 0 instead of skipping it. deletenode2, statement "x->next=null" equivalent "x=null" in deletenode since both pointers conceptually point same address, don't have same effect?
the rest of code shown below:
#include<iostream> #include<stdlib.h> using namespace std; class node { public: int data; node * next; node ( int ) { data = ; next = null; } }; bool appendtotail ( node * ptr, int ){ while (ptr->next != null) ptr = ptr->next; if (ptr==null) { return false; } else { ptr->next = new node(a); } } void printlist (node * head) { while (head!=null){ cout<<head->data<<endl; head = head->next; } } int main(void) { node * head; head = new node(1); appendtotail(head,2); appendtotail(head,3); appendtotail(head,4); appendtotail(head,5); node * = head->next->next; printlist(head); cout<<"removed:"<<endl; deletenode2(i); printlist(head); return 0; }
your answer why x doesn't change can demonstrated simpler program:
#include <iostream> void foo(int x) { x = 10; // change 10 } int main() { int num = 4; foo(num); std::cout << num; // num still 4! why? } so why num still 4? why didn't value change 10? "pass-by-value", because you're doing in pointer code.
you should either passing pointer reference, or pointer pointer (if need further explanation, fix example above make num equal 10 on return foo).
Comments
Post a Comment