c++链表排序

参考

//
// Created by zhang on 2021/3/15.
//

#include <iostream>
#include <string.h>

using namespace std;

//定义学生节点
typedef struct studentNode{
    string stuId;
//    string stuName;
//    string Id;
//    string Institute;
    string stuType;
    string Major;
//    string Routes[20];
//    string Vehicle;
//    int contactNum;
    studentNode(string _stuType, string _major, string _stuId) : stuType(_stuType), Major(_major), stuId(_stuId), next(nullptr) {}
    struct studentNode  *next;
}*stulist, stu;

bool cmp(stu a, stu b) {
    if(a.stuType != b.stuType)
        return a.stuType > b.stuType;
    else if(a.Major != b.Major)
        return a.Major > b.Major;
    else
        return a.stuId > b.stuId;
}

//链表冒泡排序
void bubbleSort(stulist &head) {
    stulist p,pre, tail;
    tail = NULL;
    while(head -> next != tail) {
        pre = head;
        p = head -> next;
        while(p -> next != tail) {
            cout<<p->Major<<" "<<p->next->Major<<endl;
            if(cmp(stu(p->stuType, p->Major, p->stuId), stu(p->next->stuType, p->next->Major, p->next->stuId))) { //p->Major > p->next->Major
                pre -> next = p ->next;
                p -> next = pre ->next->next;
                pre->next->next = p;
            } else
                p = p -> next;
            pre = pre ->next;
        }
        tail = p;
    }
}


stulist create() {
    stulist head = (stulist)malloc(sizeof(stu));
    head->next = NULL;
    return head;
}

//头插法
void insert(stulist &head, studentNode val) {
    stulist p = head;

    stulist q = (stulist)malloc(sizeof(stu));
    q->stuType = val.stuType;
    q->Major = val.Major;
    q->stuId = val.stuId;
    q->next=p->next;//新结点的下一个结点指向原先插入位置的结点
    p->next=q;
}


//输出元素
void print(stulist head) {
    stulist p = head->next;
    while(p != NULL) {
        printf("%s %s %s \n", p->stuType.c_str(), p->Major.c_str(), p->stuId.c_str());
        p = p -> next;
    }
    printf("\n");
}

int main() {
    string idList[] = {"2010","2015","2011","2014"};
    string typeList[] = {"master","master","bachelor","master"};
    string majorList[] = {"cs","es","cs","cs"};
    //创建空链表
    stulist list = create();
    //向链表插入元素
    for (int i = 0; i < 4; ++i) {
        stu p = stu(typeList[i], majorList[i], idList[i]);
        insert(list, p);
    }
    bubbleSort(list);
    print(list);
    return 0;
}

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值