【问题描述】
已知非空线性链表第1个链结点指针为list,链结点构造为
struct node{
datatype data;
node *link;
};
请写一算法,将该链表中数据域值最大的那个点移到链表的最后面。(假设链表中数据域值最大的链结点惟一)(注意:要求先写出算法的解题思路,然后再写出算法)
【输入形式】
输入为一个整数序列,整数之间以空格隔开,序列以回车结尾,输入-1结束(假设链表中吴数据-1)。
【输出形式】
输出为移动后的整数序列,整数之间以空格隔开,序列以回车结尾。
【样例输入】
3 12 4 9 5 1 -1
【样例输出】
3 4 9 5 1 12
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
struct node {
datatype data;
struct node* link;
};
void move_max_node_to_end(struct node** list) {
if (*list == NULL || (*list)->link == NULL) {
return;
}
struct node* max_node = *list;
struct node* prev_max_node = NULL;
struct node* ptr = *list;
while (ptr != NULL && ptr->link != NULL) {
if (ptr->link->data > max_node->data) {
max_node = ptr->link;
prev_max_node = ptr;
}
ptr = ptr->link;
}
if (prev_max_node == NULL) {
*list = (*list)->link;
} else {
prev_max_node->link = max_node->link;
}
ptr = *list;
while (ptr->link != NULL) {
ptr = ptr->link;
}
ptr->link = max_node;
max_node->link = NULL;
}
int main() {
struct node* list = NULL;
int input;
do {
scanf("%d", &input);
if (input != -1) {
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = input;
new_node->link = NULL;
if (list == NULL) {
list = new_node;
} else {
struct node* ptr = list;
while (ptr->link != NULL) {
ptr = ptr->link;
}
ptr->link = new_node;
}
}
} while (input != -1);
move_max_node_to_end(&list);
struct node* ptr = list;
while (ptr != NULL) {
printf("%d ", ptr->data);
ptr = ptr->link;
}
printf("\n");
while (list != NULL) {
struct node* temp = list;
list = list->link;
free(temp);
}
return 0;
}