dbq谢谢 C++或C都可以,具体样例在图片里 数据结构与算法 C++ 够三十字了吧
遍历链表找出最大的节点并记录,最后移动到最后一个位置即可。
运行结果:
代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
typedef int datatype;
struct node {
datatype data;
node* link;
};
//创建链表
struct node* creatlist()
{
int n;
struct node* head = 0, * p, * t=0;
while (1)
{
cin >> n;
p = new node;
p->data = n;
p->link = 0;
if (head == 0)
{
head = p;
t = head;
}
else
{
t->link = p;
t = p;
}
//判断是否输入结束
char ch = cin.get();
if (ch == '\n')
break;
}
return head;
}
//显示链表
void showlist(struct node* head) {
struct node* p = head;
if (p) {
cout << p->data;
p = p->link;
while (p) {
cout << " " << p->data;
p = p->link;
}
cout << endl;
}
}
//操作
struct node* move(struct node* head)
{
struct node* max, * pre=0,*p;
if (head->link == 0)
return head; //只有1个节点的情况
p = head;
max = head;
//找出最大节点
while (p) {
if (p->data > max->data) {
max = p;
}
p = p->link;
}
//如果最大节点是头节点
if (max == head) {
pre = head->link;
//找到尾节点
p = head;
while (p->link)
p = p->link;
//将头节点移动到尾部
p->link = head;
head->link = 0;
//第二个节点成为新的头节点
head = pre;
return head;
}
else {
pre = head;
p = pre->link;
while (p) {
if (p == max)
break;
pre = p;
p = pre->link;
}
//将max节点从链表中删除
pre->link = max->link;
max->link = 0;
//移动到链表尾部
p = head;
while (p->link)
p = p->link;
p->link = max;
return head;
}
}
int main()
{
struct node* head = creatlist();
//showlist(head);
head = move(head);
showlist(head);
return 0;
}
先遍历找到最大值节点以及链表尾节点
将最大值节点的前一个节点的next指向最大值节点的next
将链表尾节点的next指向最大值节点
找到最大的那个元素,换一下节点位置。如果想偷懒,把值交换一下就可以了。
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!