链表排序

来源:互联网 发布:呼伦贝尔盟616事件知乎 编辑:程序博客网 时间:2024/05/22 04:35

准备面试中,准备一些面试题。

其中比较经典的如:链表排序

代码如下:

#include <iostream>using namespace std;
/*创建节点类*/class node{public :int data;node* next;public :node(int data = -1){this->data = data;next = NULL;}};
/*创建列表*/class List{private :node* head;public :List(){head = new node(-1);if (head == NULL){printf("构造失败\n");}}void insertList(int data);void display();void sort();};/*交换节点数据(如果想交换节点,只需修改部分代码)*/void List::sort(){node* p = NULL;node* q = NULL;int temp = 0;for (p = head->next;p != NULL;p=p->next){/*有人知道下面两句的区别吗?运行看看,完全不同的结果*/      //for (q=head->next;q!=NULL;q=q->next)for (q = p->next;q != NULL;q=q->next){if (p->data > q->data){temp = q->data;q->data = p->data;p->data = temp;}}}}
/*插入链表数据*/void List::insertList(int data){if (data < 0 ){return ;}node* temp = new node(data);if (temp == NULL){printf("分配空间失败\n");return ;}temp->next = head->next;head->next = temp;}
/*链表的打印*/void List::display(){if (head == NULL){printf("List is empty!");}node* temp = head->next;while (temp != NULL){cout<<temp->data;temp = temp->next;}}int main(void){List a;a.insertList(6);a.insertList(7);a.insertList(3);a.insertList(4);a.insertList(1);a.insertList(0);a.insertList(2);a.insertList(5);a.insertList(8);a.insertList(9);a.sort();a.display();return 0;}
ps:欢迎大家指教!

原创粉丝点击