Implement an algorithm to delete a node in the middle of a one-way linked list. Assume that you can only access this node.
Example
Input: node C in one-way linked list A-> B-> C-> D-> E.
Result: No data is returned, but the linked list is a-> B-> D-> E.
Analysis: Because you cannot access the forward node of the node to be deleted, you can only move the subsequent linked list forward by copying and delete the last redundant node. Obviously, when the node to be deleted is the end point of the linked list (that is, there is no successor), there is no solution to this problem.
1 #include <iostream> 2 #include <fstream> 3 #include <assert.h> 4 5 using namespace std; 6 7 struct Node { 8 Node(): val(0), next(0) {} 9 Node( int value ): val(value), next(0) {}10 int val;11 Node *next;12 };13 14 void removeNode( Node *node );15 16 int main( int argc, char *argv[] ) {17 string data_file = "./data.txt";18 ifstream ifile( data_file.c_str(), ios::in );19 if( !ifile.is_open() ) {20 fprintf( stderr, "cannot open file: %s\n", data_file.c_str() );21 return -1;22 }23 int n = 0, k = -1;24 while( ifile >>n >>k ) {25 assert( n > 0 && k > 0 && k < n );26 Node guard, *node = &guard, *target = 0;27 for( int i = 0; i < n; ++i ) {28 node->next = new Node();29 node = node->next;30 ifile >>node->val;31 cout <<node->val <<" ";32 if( i == k-1 ) { target = node; }33 }34 cout <<endl;35 if( target ) 36 cout <<"target to remove: " <<target->val <<endl;37 else38 cout <<"target to remove: null" <<endl;39 removeNode( target );40 node = guard.next;41 cout <<"result:" <<endl;42 while( node ) {43 Node *next = node->next;44 cout <<node->val <<" ";45 delete node;46 node = next;47 }48 cout <<endl <<endl;49 }50 ifile.close();51 return 0;52 }53 54 void removeNode( Node *node ) {55 assert( node && node->next );56 node->val = node->next->val;57 while( node->next->next ) {58 node = node->next;59 node->val = node->next->val;60 }61 delete node->next;62 node->next = 0;63 return;64 }
Test File
2 11 33 11 2 33 21 2 37 114 54 96 23 45 12 457 214 54 96 23 45 12 457 614 54 96 23 45 12 45
Linked List 2.3