自定义链表

来源:互联网 发布:rfcn网络 编辑:程序博客网 时间:2024/06/07 03:15
#include <iostream>#include <time.h>#include <math.h>#include <stdlib.h>using namespace std;struct List{List(){data = 0;next =NULL;}int data;List* next;};void List_Print(List* head){List* p = head;while(p->next){cout<<" "<<p->next->data;p = p->next;}cout<<endl;}void List_Append(List* head,int data){List* p = head;while(p->next)p = p->next;p->next = new List;p->next->data = data;}void List_Remove(List* head,int data){List* p = head;while(p->next){if(p->next->data == data){List* tmp = p->next;p->next = tmp->next;delete tmp;}p = p->next;}}void List_Reverse(List* head){if(head->next == NULL || head->next->next == NULL)return;List_Reverse(head->next);List* end = head;while(end->next){end = end->next;}List* lasthead = head->next;head->next = lasthead->next;lasthead->next = NULL;end->next = lasthead;}void List_Sort(List* head){List* p = head;while(p->next){List* tmp = head;while(tmp->next  && tmp->next->data < p->next->data){tmp = tmp->next;}if(tmp->next != p->next){List* cur = p->next;p->next = cur->next;cur->next = tmp->next;tmp->next = cur;}else{p = p->next;}}}int _tmain(int argc, _TCHAR* argv[]){srand(time(NULL));List head;head.next = NULL;for (int i=0;i<10;++i){List_Append(&head,rand()&0xFF);}cout<<"初始:";List_Print(&head);/*int i;cin>>i;cout<<"删除:";List_Remove(&head,i);List_Print(&head);*/cout<<"翻转:";List_Reverse(&head);List_Print(&head);cout<<"排序:";List_Sort(&head);List_Print(&head);return 0;}

运行结果:


0 0
原创粉丝点击