单链表的创建、排序、逆置等

#include<iostream>
#include<cstdlib>
using namespace std;
//定义链表节点;
typedef struct Node{
    int data;
    Node*next;
}node;
 
//创建链表;
node*Create_list()
{
  node *head;
  node*p;
  node*s;
  int x;
  head=(node*)malloc(sizeof(node));
  p=head;
  int temp=1;
 cout<<"please enter the data,(entre '0' to end ):";
 while(temp) {     cin>>x;     if(0!=x){   s=(node*)malloc(sizeof(node));   s->data=x;   p->next=s;   p=s;}   else    temp=0; }  head=head->next;  p->next=NULL;  return head;}int length_list(node*head)//链表长度;{  int n=0;  node*p=head;  while(p!=NULL)  { p=p->next;  ++n;}  return n;}void print_list(node*head)//打印链表;{   node*p; if(NULL==head) cout<<"this is null list !"; else  p=head; while(NULL!=p)  {cout<<p->data<<"\t"; p=p->next;} cout<<endl;}node*sort_list(node*head) //链表排序;{   node*p; int temp; int n=length_list(head); if(NULL==head||head->next==NULL)  return head; else for(int j=1;j<n;++j)//使用冒泡排序;  {     p=head;   for(int i=0;i<n-j;++i){   if(p->data>p->next->data)   {      temp=p->data;      p->data=p->next->data;      p->next->data=temp;   }   p=p->next;   } } return head;}node*reverse_list(node*head) //链表逆置;{ node*p1,*p2,*p3; while((NULL==head)||(NULL==head->next))  return head; p1=head; p2=p1->next; p1->next=NULL; while(NULL!=p2) {  p3=p2->next;  p2->next=p1;  p1=p2;  p2=p3; } return p1;}//删除链表头元素;node*delete_headelement(node*head){ node*p=head; if(NULL==p||NULL==p->next)  return NULL; else  head=head->next; free(p); return head;}//提供一个单链表,不知道元素个数,只遍历一次,求中间元素;int middle_ele_list(node*head){ node*p1,*p2; p1=head; p2=head; while((p2->next!=NULL)&&(p2->next->next!=NULL)) {      p2=p2->next->next;  p1=p1->next; } return p1->data;}//求链表倒数第m个元素;int backwords_list(node*head,int m){ node*p=reverse_list(head); //先逆置链表; for(int i=1;i<m;++i)  p=p->next; return p->data;}node*Merge_list(node*a,node*b) //将两个有序(升序)的链表连接后,仍然有序;{ node*head=NULL; node*temp=NULL; if(a==NULL) return b; else if(b==NULL) return a; if(a->data>b->data) { head=b;b=b->next;} else { head=a;a=a->next;} temp=head; while((a!=NULL)&&(b!=NULL)) {    if((a->data)>(b->data)) { temp->next=b; temp=b; b=b->next; } else if(a->data<=b->data) { temp->next=a; temp=a; a=a->next; } } if(a==NULL) while(b!=NULL) { temp->next=b; temp=b; b=b->next; } else while(a!=NULL) { temp->next=a; temp=a; a=a->next; } temp->next=NULL; return head;}node*RecurrenceMerge(node*a,node*b)//递归 合并两个升序的链表,合并后仍有序;{ if(a==NULL) return b; else if(b==NULL)   return a; node*head=NULL;     if(a->data>b->data) { head=b; head->next=RecurrenceMerge(a,b->next); } else { head=a; head->next=RecurrenceMerge(b,a->next); } return head;}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值