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; idata = 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
本文介绍了一种仅通过访问单链表中间节点来删除该节点的方法,并提供了相应的代码实现。针对不同节点类型(头节点、中间节点、尾节点),文中详细解释了如何避免循环引用的问题。
17万+

被折叠的 条评论
为什么被折叠?



