单链表的选择排序

【说明】:

  本文是左程云老师所著的《程序员面试代码指南》第二章中“单链表的选择排序”这一题目的C++复现。

  本文只包含问题描述、C++代码的实现以及简单的思路,不包含解析说明,具体的问题解析请参考原书。

  感谢左程云老师的支持。

【题目】:

  给定一个无序单链表的头节点 head,实现单链表的选择排序。

  要求:额外的空间复杂读为 O(1)。

 【思路】:

  解法:选择排序

【编译环境】:

  CentOS6.7(x86_64)

  gcc 4.4.7

 【实现】:

  实现及测试代码:

  1 /*
  2  *文件名:list_sort.cpp
  3  *作者
  4  *摘要:单链表的选择排序
  5  */
  6 
  7 #include <iostream>
  8 
  9 using namespace std;
 10 
 11 class Node
 12 {
 13 public:
 14     Node(int data)
 15     {
 16         value = data;
 17         next = NULL;
 18     }
 19 public:
 20     int value;
 21     Node *next;
 22 };
 23 
 24 Node* getSmallestPreNode(Node *head)    //获取未排序链表中最小节点的前一个节点
 25 {
 26     Node *smallPre = NULL;
 27     Node *small = head;
 28     Node *pre = head;
 29     Node *cur = head->next;
 30     while(NULL != cur)
 31     {
 32         if(cur->value < small->value)
 33         {
 34             smallPre = pre;
 35             small = cur;
 36         }
 37         pre = cur;
 38         cur = cur->next;
 39     }
 40     return smallPre;
 41 }
 42 
 43 Node* selectionSort(Node *head)
 44 {
 45     Node *tail = NULL;    //已排序部分的尾部
 46     Node *cur = head;     //未排序部分的头部
 47     Node *smallPre = NULL;
 48     Node *small = NULL;
 49     while(NULL != cur)
 50     {
 51         small = cur;
 52         smallPre = getSmallestPreNode(cur);
 53         if(NULL != smallPre)
 54         {
 55             small = smallPre->next;
 56             smallPre->next = small->next;
 57         }
 58         cur = cur == small ? cur->next : cur;
 59         if(NULL == tail)
 60             head = small;
 61         else
 62             tail->next = small;
 63         tail = small;
 64     }
 65     return head;
 66 }
 67 
 68 //打印链表
 69 void printList(Node *head)
 70 {
 71     while(NULL != head)
 72     {
 73         cout << head->value << " ";
 74         head = head->next;
 75     }
 76     cout << endl;
 77 }
 78 
 79 int main()
 80 {
 81     Node *head = NULL;
 82     Node *ptr = NULL;
 83     
 84     for(int i =8;i>0;i--)//构造链表
 85     {
 86         if(NULL == head)
 87         {    
 88             head = new Node(i);
 89             ptr = head;
 90             continue;
 91         }
 92         ptr->next = new Node(i);
 93         ptr = ptr->next;    
 94     }
 95     cout << "Before sorted:" << endl;
 96     printList(head);
 97     cout << "After sorted:" << endl;
 98     head = selectionSort(head);
 99     printList(head);
100     return 0;
101 }
View Code

 

注:

  转载请注明出处;

  转载请注明源思路来自于左程云老师的《程序员代码面试指南》。

posted @ 2016-04-28 09:19  PrimeLife  阅读(1867)  评论(0编辑  收藏  举报