Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node.
EXAMPLE
Input: the node ‘c’ from the linked list a->b->c->d->e Result: nothing is returned, but the new linked list looks like a->b->d->e
Solution:
Since only the removed node of the singly linked list is given, we can only find all the next but not going back. So we can copy the next node of this removable node so as to "remove" it.
One thing should notice is the corner condition:
1. head 2. middle 3. last one
for 1,2 is fine. For 3, we cannot use this method so can't solve it.
Here is the fully code:
//http://hawstein.com/posts/2.3.html
//date: Jan 9, 2013
#include
using namespace std;
struct node{
int data;
node* next;
};
node* init(int* a, int n){
node *head, *p;
for(int i=0; i
data = a[i];
if(i==0){
head = p = nd;
continue;
}
p->next = nd;
p = nd;
}
return head;
}
void print(node* a){
while (a!= NULL){
cout << a->data << " " ;
a= a->next;
}
cout << endl;
}
bool remov(node* c){
if(c==NULL || c->next == NULL) return false; // if c is last node, can't
// solve it...
node* q=c->next;
c->data = q->data;
c->next = q->next;
delete q;
return true;
}
int main(){
int n = 10;
int a[] = {
10,9,8,7,6,5,4,3,2,1
};
node* head = init(a,n);
int cc = 3;
node *c = head;
for(int i=1; i
next;
}
print(head);
if(remov(c)){
print(head);
}
return 0;
}
Output:
Executing the program....
$demo
10 9 8 7 6 5 4 3 2 1
10 9 7 6 5 4 3 2 1