zoukankan      html  css  js  c++  java
  • C++链表归并排序示例

    /*
     * description:        链表归并排序示例
     * writeby:            nick
     * date:            2012-10-23 16:35
     *
     */
    
    #include <iostream>
    #define maxN 10
    
    using namespace std;
    
    struct node
    {
        int item;
        node *next;
        node(int n){item=n; next=0;}
    };
    typedef node *link;
    
    link merge(link a, link b)    //合并a b 链表
    {
        node dummy(0);
        link head=&dummy, c=head;
        while((a!=0) && (b!=0))
        {
            if(a->item < b->item)
            {
                c->next=a; c=a; a=a->next;
            }
            else
            {
                c->next=b; c=b; b=b->next;
            }
        }
        c->next = (a==0)? b : a;
        return head -> next;
    }
    
    link mergesort(link c)
    {
        if(c==0 || c->next==0) return c;
        link a=c, b=c->next;
        while(b!=0 && b->next!=0)
        {
            a=a->next; b=b->next->next;
        }
        b=a->next; a->next=0;    //把c分成两部分
        return merge(mergesort(c), mergesort(b));
    }
    
    int main()
    {
        link head1 = new node(2);
        head1->next = new node(4);
        head1->next->next = new node(6);
        head1->next->next->next = new node(3);
        head1->next->next->next->next = new node(5);
    
        link head = mergesort(head1);
    
        while(head != 0)
        {
            cout << head->item;
            head = head->next;
        }
    
        return 0;
    }
  • 相关阅读:
    html----有关图像
    前端开发初学者
    angular js 正序倒叙
    viewpager无线轮播获取网络图片
    angular js 球星
    angular js shopping
    angular js 公告墙
    Android 常用正则表达式
    Android 内存泄漏
    TCP/IP,必知必会的
  • 原文地址:https://www.cnblogs.com/wouldguan/p/2738307.html
Copyright © 2011-2022 走看看