CareerCup2.3 删除最中间那个,或者删除给出任意一个节点(只能得到这个节点的pointer)

/*
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
*/

//这个题目的意思是不给head 和tail,只给了middle的一个需要删除的node
//这样的话,算法就变成了 1先把后一个node copy过来
//                       2然后删掉后一个node
//!!!!!!!!!!!!!!!!!given only access to that node  只能获得那个node

/*****************************************************************************/
//若是删除中间那个元素的话,可以考虑类似2.2的方法  2.2是中间差n
//这个可以是 p2 p1 p2每次move 2steps p1每次1step

#include<iostream>

using namespace std;

struct Node 
{
	char data;
	Node *next;
};
void create(Node *head)
{
	Node *temp=head;
	char tempCommand='Y';

	cout<<"Please input data"<<endl;
	cin>>temp->data;
	temp->next=NULL;

	while (tempCommand=='Y'||tempCommand=='y')
	{
		Node *newtemp=new Node;
		cout<<"Please input data"<<endl;
		cin>>newtemp->data;
		newtemp->next=NULL;
		temp->next=newtemp;

		temp=newtemp;
		cout<<"continue?"<<endl;
		cin>>tempCommand;
	}



}

void printLinkedList(Node *head)
{
	Node *temp=head;
	while(temp->next!=NULL)
	{
		cout<<temp->data<<"->";
		temp=temp->next;
		
	}
	cout<<temp->data<<endl;
}

/*
void deleteMiddle(Node *head)
{
	int length=1;
	Node *temp=head;

	while(temp->next!=NULL)
	{
		++length;
		temp=temp->next;
	}
	
	if(length%2==0)
	{
		cout<<"there are two middle nodes"<<endl;
	}
	else
	{
	
		temp=head;
	for(int i=1;i<(length/2);i++)
	{
		temp=temp->next;
	}
	Node *tempNext=temp->next;
	temp->next=tempNext->next;
	delete(tempNext);
	}
}
*/

void deleteNode(Node *D_node)
{

	//1 要指出
	if(D_node->next==NULL || D_node==NULL)
	{
		cout<<"FAILED"<<endl;
	}
	//2 copy,然后删除下一个
	else
	{
		D_node->data=D_node->next->data;
		Node *temp=D_node->next;
		D_node->next=D_node->next->next;
		delete(temp);
	}
}


void main()
{
	Node *head=new Node;
	create(head);
	printLinkedList(head);
	deleteNode(head->next);
	printLinkedList(head);


}

题目的意思是删除任意一个节点,但不给head的指针。

这样的话技巧就在,先把后一个节点的内容copy给需要被删的节点,然后删除下个节点,这样会节省时间,代码如下。



如果要删除中间那个节点,这样有点儿类似2.2,p2 p1 that point to the head, p2 moves 2 steps forword and p1 moves 1 step forward in the iteration


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值