编写函数MoveMaxToTail(),实现查找单链表中值最大的结点,并将其移动到链表尾部,注意其他结点的相对次序不变。要求尽量具有较高的时间效率。
例如输入8 12 46 30 5,输出为8 12 30 5 46
函数接口定义:
void MoveMaxToTail (LinkList H );
裁判测试程序样例:
#include<stdio.h>
#include<stdlib.h>typedef int DataType;
struct Node
{
DataType data;
struct Node* next;
};
typedef struct Node *PNode;
typedef struct Node *LinkList;void MoveMaxToTail(head);
LinkList SetNullList_Link()
{
LinkList head = (LinkList)malloc(sizeof(struct Node));
if (head != NULL) head->next = NULL;
else printf("alloc failure");
return head;
}void CreateList_Tail(struct Node* head)
{
PNode p = NULL;
PNode q = head;
DataType data;
scanf("%d", &data);
while (data != -1)
{
p = (struct Node*)malloc(sizeof(struct Node));
p->data = data;
p->next = NULL;
q->next = p;
q = p;
scanf("%d", &data);
}
}
void MoveMaxToTail (LinkList H )
{
@@
}
void print(LinkList head)
{
PNode p = head->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
}
void DestoryList_Link(LinkList head)
{
PNode pre = head;
PNode p = pre->next;
while (p)
{
free(pre);
pre = p;
p = pre->next;
}
free(pre);
}int main()
{
LinkList head = NULL;
head = SetNullList_Link();
CreateList_Tail(head);
MoveMaxToTail(head);
print(head);
DestoryList_Link(head);
return 0;
}
输入样例:
8 12 46 30 5 -1
输出样例:
8 12 30 5 46
void MoveMaxToTail(LinkList H)
{
LinkList p = H->next; // 当前节点指针
LinkList s = H; // 当前节点的前一个节点指针
LinkList max = p; // 最大值节点指针
LinkList maxPrev = H; // 最大值节点的前一个节点指针
// 找到最大值节点和其前一个节点
while (p != NULL)
{
if (max->data < p->data)
{
max = p;
maxPrev = s;
}
s = p;
p = p->next;
}
// 如果最大值节点已经在链表尾部,则无需移动
if (max->next == NULL)
{
return;
}
// 将最大值节点从链表中删除
maxPrev->next = max->next;
// 将最大值节点移动到链表尾部
p = H;
while (p->next != NULL)
{
p = p->next;
}
p->next = max;
max->next = NULL;
}