实验思路:
- 寻找链表的中点,把链表分为两部分。
- 后半部分进行逆置。
- 把前半部分链表和后半部分链表结合起来。
核心代码:
1.查找中点
Node* fast = head->next;
Node* slow = head->next;
Node* slowpre = slow;
while (fast != nullptr && slow != nullptr && fast->next!= nullptr)
{
slowpre = slow;
slow = slow->next;
fast = fast->next->next;
}
slowpre->next = nullptr;
2.倒序
Node* head2=new Node;
head2->next = nullptr;
Node* p, * s;
s= slow;
p = slow->next;
while (p)
{
s->next = head2->next;
head2->next = s;
s = p;
p = p->next;
if(p==nullptr)
{
s->next = head2->next;
head2->next = s;
}
}
Node* second = head2->next;
delete head2;
- 合并链表
Node *first=head->next;
Node *head1=first;
Node *tail=head1;
first=first->next;
while(first!=nullptr && second!=nullptr)
{
tail->next=second;
second=second->next;
tail=tail->next;
tail->next=first;
first=first->next;
tail=tail->next;
}
tail->next=(first==nullptr)?second:first;
全部代码:
#include<iostream>
using namespace std;
struct Node{
int date;
Node* next = nullptr;
};
int main()
{
Node *head=new Node;
Node *re=head;
int a[11];
for (int i = 0; i < 11; ++i)
a[i] = i + 1;
for (int i = 0; i < 11; ++i)
{
Node *s=new Node;
s->date=a[i];
s->next=re->next;
re->next=s;
re=s;
}
//表达数据
Node* x1 = head->next;
if (x1 != nullptr)
{
cout << "初始数据为:" << endl;
while (x1 != nullptr)
{
cout << " " << x1->date;
x1 = x1->next;
}
cout << endl;
}
else
cout << "表中无数据" << endl;
//查找中点
Node* fast = head->next;
Node* slow = head->next;
Node* slowpre = slow;
while (fast != nullptr && slow != nullptr && fast->next!= nullptr)
{
slowpre = slow;
slow = slow->next;
fast = fast->next->next;
}
slowpre->next = nullptr;
//倒序
Node* head2=new Node;
head2->next = nullptr;
Node* p, * s;
s= slow;
p = slow->next;
while (p)
{
s->next = head2->next;
head2->next = s;
s = p;
p = p->next;
if(p==nullptr)
{
s->next = head2->next;
head2->next = s;
}
}
Node* second = head2->next;
delete head2;
//合并链表
Node *first=head->next;
Node *head1=first;
Node *tail=head1;
first=first->next;
while(first!=nullptr && second!=nullptr)
{
tail->next=second;
second=second->next;
tail=tail->next;
tail->next=first;
first=first->next;
tail=tail->next;
}
tail->next=(first==nullptr)?second:first;
//表达数据
Node* p1 = head1;
if (p1 != nullptr)
{
cout << "变化后数据为:" << endl;
while (p1 != nullptr)
{
cout << " " << p1->date;
p1 = p1->next;
}
cout<<endl;
}
else
cout << "表中无数据" << endl;
Node* p2 = head;
while (p2)
{
Node* q = p2;
p2 = p2->next;
delete q;//从头开始删除
}
return 0;
}
结果截图: