- 链表的算法操作借助画图可以帮助分析和理解
#include
#include
#include
#include
#include
using namespace std;
struct LinkNode
{
int val;
LinkNode next;
LinkNode(int val, LinkNodenext = nullptr)
{
this->val = val;
this->next = next;
}
};
LinkNode* create(int n)
{
srand((unsigned)time(NULL));
LinkNode *dummy = new LinkNode(-1), *cur = dummy;
for (int i = 0; i < n; i++)
{
LinkNode *temp = new LinkNode(i + 1);
cur->next = temp;
cur = cur->next;
}
return dummy->next;
}
LinkNode * SwapNodesInPairs(LinkNode *head)
{
LinkNode *dummy = new LinkNode(-1), *pre = dummy;
dummy->next = head;
LinkNode cur = head;
LinkNode t = cur->next;
while (cur != nullptr && t != nullptr)
{
LinkNode temp = t->next;
t->next = cur;
pre->next = t;
pre = cur;
pre->next = nullptr;
cur = temp;
if (cur)
{
t = cur->next;
}
else
{
break;
}
}
if (cur)
{
pre->next = cur;
}
return dummy->next;
}
void display(LinkNode head)
{
LinkNodetemp = head;
while (temp)
{
cout << temp->val << " ";
temp = temp->next;
}
cout << endl;
}
int main()
{
LinkNode head = create(8);
display(head);
LinkNode *head1 = SwapNodesInPairs(head);
display(head1);
system(“pause”);
return 0;
}