c语言 单链表 选择排序+归并排序

指针完全不会用了,为了面试,写写~~

 

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
struct node{
    int data;
    node * next;
};
node *creat(){
    struct node *head, *tail, *p;
    head = NULL;
    tail = NULL;
    p = NULL;
    int aa, bb;
    while( scanf("%d", &aa) && aa!= 0){ // 输入为0时停止
        p = (struct node *)malloc(sizeof(struct node));
        p->data = aa;
        if( head == NULL){
            head = p;
            tail = head;
        }
        else {
            tail->next = p;
            tail = p;
        }
    }
    tail->next = NULL;
    return head;
}
node *merge_sort(node *l1, node *l2){ 
    node *tmp1, *tmp2, *tmp, *head, *tail;
    if( l1->data <= l2->data){
        head = l1;
        tmp1 = l1->next;
        tmp2 = l2;
    }
    else{
        head = l2;
        tmp1 = l1;
        tmp2 = l2->next;
    }
    tail = head;
    while(1){
        if( tmp1 == NULL){
            tail = tail->next = tmp2;
            break;
        }
        if( tmp2 == NULL){
            tail = tail->next = tmp1;
            break;
        }
        if( (tmp1->data) <= (tmp2->data)){
            tail = tail->next = tmp1;
            tmp1 = tmp1->next;
        }
        else{
            tail = tail->next = tmp2;
            tmp2 = tmp2->next;
        }
    }
    return head;
}
void print(node * tmp){
    while( tmp != NULL){
        cout<<tmp->data<<"  ";
        tmp = tmp->next;
    }
    printf("\n");
}
void sort(node *p){
    node *head, *tail, *tmp1, *tmp2;
    int aa;
    for( tmp1 = p; tmp1!= NULL; tmp1 = tmp1->next){
        for( tmp2 = tmp1->next; tmp2!= NULL; tmp2= tmp2->next){
            if( tmp1->data >= tmp2->data){
                aa = tmp1->data;
                tmp1->data = tmp2->data;
                tmp2->data = aa;
            }
        }
    }
}
int main(){
	freopen("1.txt", "r", stdin);
    node *l1, *l2 , *tmp;
    l1 = creat();
    l2 = creat();
    sort(l1);
    sort(l2);
    tmp = merge_sort(l1, l2);
    print(tmp);
    //l2 = creat();
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值