Ch2-3: remove the middle node in a singly linked list

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值