您的位置:首页 > 其它

单链表交换任意两个元素(不包括表头)

2010-07-08 15:59 330 查看
面试题
思路:
假设交换A,B,那么交换A和B的next指针,以及AB直接前驱的next指针;
特殊情况是AB相邻,做特殊处理即可。

struct node

{
int data;
node* next;
};

// find the previous node of p in the singly linked list head
node* FindPre(node*head, node*p)
{
node*q = head;
while(q)
{
if(q->next == p)
{
return q;
}
else
{
q = q->next;
}
}
return NULL;
}

// swap the two nodes p & q in the singly linked list head
// Pre-condition: p, q are not head of the list
node* swap(node*head, node*p, node*q)
{

if ( head == NULL || p == NULL || q == NULL )

{
cout<<"invalid parameter: NULL"<<endl;
return head;
}

// P->Q
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)// Q->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;
// node* after_q = q->next;
p->next = q->next; // p->after_q
q->next = after_p; // q->after_p
pre_p->next = q; // pre_p->q
pre_q->next = p; // pre_q->p
}

return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐