C++ Link list insert swop -
i want insert 2 4 , 4 2. getting errors swop. how fix code below swop.
#include <iostream> struct nodetype { int info ; nodetype* link ; }; int main() { nodetype* ptr ; nodetype* list ; ptr = new nodetype; ptr->info = 1; list = new nodetype; ptr->info = 2; list->link = ptr; ptr = new nodetype; ptr->info = 3; ptr = new nodetype; list->info = 4; ptr->link = null; list->link->link->link = ptr; unsigned count = 1 ; ptr = list ; while ( ptr ) { std::cout << "node #" << count++ << ':' << ptr->info << '\n' ; ptr = ptr->link ; } } i have tried various ways swop occur , getting compiler errors. thanks
nodetype* ptr ; nodetype* list ; ptr = new nodetype; ptr->info = 1; the pointer ptr points node contains 1.
list = new nodetype; ptr->info = 2; now list points node, , node ptr points contains 2.
list->link = ptr; now 1 node connected other.
ptr = new nodetype; ptr->info = 3; now ptr points node, containing 3.
ptr = new nodetype; now ptr points another node, , node containing 3 has been lost.
list->info = 4; now first node in list contains 4.
ptr->link = null; all right.
list->link->link->link = ptr; now trying iterate past end of list (which has 2 nodes). dereference invalid pointer, causes undefined behavior; you're lucky if access violation error.
you must study pointers more before attempt swap in middle of list.
Comments
Post a Comment