两个有序链表合成一个有序链表

本文深入探讨了链表数据结构的基本概念和操作,通过实现链表节点定义、双链表合并、有序插入等核心功能,展示了链表在数据排序和组织中的强大应用能力。

#include<stdio.h>
#include<stdlib.h>
typedef struct list
{
 int data;
 struct list*next;
}List;
List*hebin(List*head1,List*head2)
{ List*head,*rear;
 if(head1==NULL) return head2;
 if(head2==NULL) return head1;
 if(head1->data<head2->data)
 {
  rear=head=head1;
  head1=head1->next;
  } 
  else
  {
   rear=head=head2;
   head2=head2->next;
  }
  while(head1!=NULL && head2!=NULL)
  {
   if(head1->data<head2->data)
   {
    rear->next=head1;
   rear=head1;
   head1=head1->next; 
   } 
   else
   {
   rear->next=head2;
   rear=head2;
   head2=head2->next;  
   }
  }
  if(head1!=NULL)
   rear->next=head1;
 else
  rear->next=head2;
  return head;
}
List*insert_list_order(List*head,int data)
{ List*newnode=(List*)malloc(sizeof(List));
 List*p=head;
 newnode->data=data;
 newnode->next=NULL;
 if(head==NULL) return newnode;
 if(head->data>data)
 {
  newnode->next=head;
  head=newnode;
  return head;
 }
 while(head->next && head->next->data<data)
 {
  head=head->next;
 }
 if(!head->next) head->next=newnode;
 else
 {
  newnode->next=head->next;
  head->next=newnode; 
 }
 return p;
}
void print_list(List*head)
{
 while(head)
 {
  printf("%d\n",head->data);
  head=head->next;
 }
}
int main()
{
 int i,j;
 List*head1=NULL;
 List*head2=NULL;
 List*head;
 for(i=0;i<10;i+=2)
 {
  head1=insert_list_order(head1,i); 
 }
 printf("head1:\n");
 print_list(head1); 
 for(j=1;j<20;j+=3)
 {
  head2=insert_list_order(head2,j); 
 }
 printf("head2:\n");
 print_list(head2);
 head=hebin(head1,head2);
 printf("head:\n");
 print_list(head); 
}

转载于:https://www.cnblogs.com/ITfeng/archive/2012/05/08/2490689.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值