链表的就地插入排序

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

template <class T>
struct Entry;

template <class T>
struct Link_head{
  Entry<T>* next;
  int size;
};

template <class T>
struct Entry{
  Entry<T>* next;
  T* element;
};

template <class T>
Link_head<T>*
create_link(T* array, int n)
{
  Link_head<T>* head=new Link_head<T>;
  Entry<T>** ptr=&head->next;
  for(int i=0; i<n; ++i){
    Entry<T>* entry_elem=new Entry<T>;
    T* element=new T(array[i]);
    entry_elem->element=element;
    *ptr=entry_elem;
    ptr=&entry_elem->next;
  }
  *ptr=NULL;
  head->size=n;
  return head;
}

template <class T>
void
print_link(Link_head<T>* head)
{
  Entry<T>* entry=head->next;
  while(entry != NULL){
    cout<<*entry->element<<endl;
    entry=entry->next;
  }
}

template <class T>
void
link_sort(Link_head<T>* head)
{
  Entry<T>* p = head->next;
  Entry<T>* r; //r 是 p的后继
  Entry<T>* q;
  head->next=NULL;
  while(p != NULL){
    r=p->next;
    q=(Entry<T>*)head;
    while(q->next != NULL && *q->next->element<*p->element){
      q=q->next;
    }
    p->next=q->next;
    q->next=p;
    p=r;
  }
}

int
main()
{
  int array[]={20,3, 40, 5, 6, 89, 9};
  int n = sizeof(array)/sizeof(int);
  Link_head<int>* head = create_link(array, n);
  link_sort(head);
  print_link(head);
}
posted @ 2011-09-01 07:53  Richard Zhong  阅读(343)  评论(0编辑  收藏  举报