c语言数据结构线性链表的结点移动

【问题描述】
已知非空线性链表第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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值