【正确答案】
【答案解析】对于单链表而言,假设交换的结点为A与B,那么需要交换A与B的next指针以及AB直接前驱的next指针。需要注意的特殊情况:当A与B相邻时,此时需要做特殊处理;如果A与B元素相同,就没有必要交换;如果A与B结点中有一个是表头,也不交换。
程序示例如下:
struct node
{
int data;
node* next;
};
node* FindPre(node*head,node*p)
{
node *q=head;
while(q)
{
if(q->next==p)
return q;
else
q=q->next;
}
return NULL;
}
node* Swap(node *head,node *p,node *q)
{
if(head==NULL‖P==NULL‖q==NULL)
{
cout<<"invalid parameter:NULL"<<endl;
return head;
}
if(p->data==q->data)
return head;
if(p->next==q)
{
node* pre_p=FindPre(head,p);
pre_p->next=q;
p->next=q->next;
q->next=p;
}
else if(q->next==p)
{
node* pre_q=FindPre(head,q);
pre_q->next=p;
q->next=p->next;
p->next=q;
}
else if(p!=q)
{
node* pre_p=FindPre(head,p);
node* pre_q=FindPre(head,q);
node* after_p=p->next;
p->next=q->next;
q->next=after_p;
pre_p->next=q;
pre_q->next=p;
}
return head;
}