链表表示的直接插入排序算法

写算法的时候,才能更深刻的意识到自己的不足.对自己的水平的提高和进步有很大的帮助.几乎花了6个小时的时间.发现自己真的水平很低.

需要不断的完善自己.努力提高.不想写很多注释,给自己看的话,虽然注释能让自己以后看能更省时间,不过不必要了

//设计一个用链表表示的直接插入排序算法 #include <stdio.h> #include <stdlib.h> #define length 5 #define MAX 0 //#define null 0 struct Node{ int data;//数据域 struct Node * next;//指针域 }; /**************************************************************************************   *函数名称:insert   *函数功能:在链表中插入元素.   *输入:head 链表头指针,p新元素插入位置,x 新元素中的数据域内容   *输出:无 *************************************************************************************/ void insert(Node * head,int p,int x){ Node * tmp = head; //for循环是为了防止插入位置超出了链表长度 for(int i = 0;i<p;i++) { if(tmp == NULL) return ; if(i<p-1) tmp = tmp->next; } Node * tmp2 = new Node; tmp2->data = x; tmp2->next = tmp->next; tmp->next = tmp2; } /* *************************************************************************************   *函数名称:del   *函数功能:删除链表中的元素   *输入:head 链表头指针,p 被删除元素位置   输出:被删除元素中的数据域.如果删除失败返回-1   **************************************************************************************/ int del(Node * head,int p){ Node * tmp = head; for(int i = 0;i<p;i++) { if(tmp == NULL) return -1; if(i<p-1) tmp = tmp->next; } int ret = tmp->next->data; tmp->next = tmp->next->next; return ret; } void print(Node *head){ for(Node *tmp = head; tmp!=NULL; tmp = tmp->next) printf("%d ",tmp->data); printf("/n"); } void Display(Node * head) { //Node * pre; if(head->next == NULL) return; else { //pre = head->next; /* { printf("%d ",pre->data); pre = pre->next; }while(pre->next != NULL); */ for(Node * tmp = head->next; tmp!=NULL; tmp = tmp->next) //用for循环可以避免用while循环出现的内存出错************************************** Very important printf("%d ",tmp->data); printf("/n"); return; } } void InsertSort(Node * head,int n,int i) { if( i == 1) { Node * node; node = new Node; node->data = n; node->next = head->next; head->next = node; return; }else { Node * node; node = new Node; node->data = n; for(Node * pre = head; pre != NULL; pre = pre->next) { if(n > pre->data && pre->next == NULL) { node->next = NULL; pre->next = node; }else if(n > pre->data && n < pre->next->data) { node->next = pre->next; pre->next = node; } } } return; } int main(){ void InsertSort(Node * head,int n,int i); void Display(Node * head); Node * head; head = new Node; head->data = -1; head->next=NULL; int count = 1; int n; while(count <= length) { printf("Please Input a number for Sort:"); scanf("%d",&n); InsertSort(head,n,count); count++ ; Display(head); } return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值