如上题目所示:写代码实现题目要求。 我通过改变结点next 指针位置实现了题目要求,没有用到额外空间,但是需要遍历链表n/2次,各位有什么好的方法欢迎在下面评论,谢谢!。
#include <iostream>
using namespace std;
struct node
{
int elem;
node* next;
};
void insert(node **rootp,int value)
{
node *newNode=new node;
if (newNode==NULL)
{
cout<<" memory error \n";
}
newNode->elem=value;
newNode->next=*rootp;
(*rootp)=newNode;
}
void PrintList(node *root)
{
if (root==NULL)
{
cout<<"empty list \n";
return ;
}
while (root)
{
cout<<root->elem<<" ";
root=root->next;
}
cout<<endl;
}
//找到每次需要更改指针的结点,发现一个规律每次需要改变的结点都可以通过从root结点走链表长度减一步得到
node * addressofnode(node *root,int count)
{
while (count&&root->next)
{
root=root->next;
count--;
}
return root;
}
void ModifyList(node *root,int len)
{
if (root==NULL||root->next==NULL)
{
return ;
}
node *p=root;
node *pnext=NULL;
node *q=NULL;
pnext=root->next;
int count=len-1;
//循环结束条件是当pnext下个结点是寻找到q指针指向的结点,意味着pnext指向了链表尾结点
while (q!=pnext->next)
{
q=addressofnode(root,count);
p->next=q;
q->next=pnext;
p=pnext;
//如果pnext下一个结点是q意味着pnext不需要往后移动!
if (q!=pnext->next)
{
pnext=pnext->next;
}
}
pnext->next=NULL;
}
int main()
{
int a[]={5,6,7,8,10};
node *LA=NULL;
for (int i=0;i<5;i++)
{
insert(&LA,a[i]);
}
PrintList(LA);
ModifyList(LA,5);
PrintList(LA);
return 0;
}