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