您的位置:首页 > 其它

【算法题】交换单链表任意两个元素

2017-05-29 10:08 246 查看
首先添加虚拟头结点

然后找到指定节点的前驱节点

再然后分两种情况进行交换:相邻节点交换和非相邻节点交换

#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;

struct ListNode
{
ListNode* next;
int value;
};

bool List_insert(ListNode ** phead, int x, int i)
{
//空指针
if (phead == NULL)
{
return 0;
}
ListNode * pCurrent(NULL);

//头插入
if (i==1)
{
pCurrent = *phead;
ListNode * pNew = new ListNode;
pNew->value = x;
pNew->next = pCurrent;
*phead = pNew;
return 1;
}
//非头插入
pCurrent = *phead;
ListNode * pfront(NULL);
int k(1);
while (k < i && pCurrent != NULL)
{
pfront = pCurrent;
pCurrent = pCurrent->next;
k++;
}
if (k != i)
{
return 0;
}
ListNode * pNew = new ListNode;
pNew->value = x;
pNew->next = pCurrent;
pfront->next = pNew;
return 1;
}

void List_print(ListNode * phead)
{
while (phead!=NULL)
{
cout << phead->value;
phead = phead->next;
}
cout << endl;
}

ListNode * findpre(ListNode* phead,int v)//寻找前驱节点
{
if (phead==NULL)
{
return phead;
}
for (auto i = 0; i < v-1;i++)
{
if (phead!=NULL)
{
phead = phead->next;
}
}
return phead;
}

ListNode* swapnode(ListNode * head,int v1,int v2)//交换第v1和v2个节点
{
if (head==NULL|| head->next==NULL||v1==v2)
{
return head;
}
ListNode dummy;
dummy.next = head;

if (v1>v2)
{
std::swap(v1, v2);
}

ListNode * v1_pre = findpre(&dummy, v1);
ListNode * v2_pre = findpre(&dummy, v2);

if (v2_pre == NULL||v2_pre->next == NULL)
{
return head;
}

if (v1_pre->next == v2_pre)//相邻v1 == v2_pre
{
ListNode* v2_node = v2_pre->next;
v1_pre->next = v2_node;
v2_pre->next = v2_node->next;
v2_node->next = v2_pre;
}
else
{
ListNode * v1_node = v1_pre->next;
ListNode * v2_node = v2_pre->next;
std::swap(v1_node->next, v2_node->next);
std::swap(v1_pre->next, v2_pre->next);
}
return dummy.next;
}

int main()
{
ListNode * phead = NULL;
List_insert(&phead, 1, 1);
List_insert(&phead, 2, 1);
List_insert(&phead, 3, 1);
List_insert(&phead, 4, 1);
List_insert(&phead, 5, 1);
List_insert(&phead, 6, 1);
List_print(phead);

phead = swapnode(phead,5,7 );
List_print(phead);
phead = swapnode(phead, 5, 1);
List_print(phead);

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