编写函数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
输入样例:
12 8 46 30 5 -1
输出样例:
12 8 30 5 46
代码如下:
void MoveMaxToTail(LinkList H)
{
LinkList pre=H,r=H;
LinkList q=pre->next;
while(q)
{
if(pre->data<q->data)
{
pre=q;
}
q=q->next;
}
while(r->next!=pre) r=r->next;
q=H;
while(q->next) q=q->next;
if(pre->next==NULL)
return;
else
{
r->next=pre->next;
pre->next=NULL;
q->next=pre;
}
}