建立有序链表算法

#include "stdafx.h"
#include "stdlib.h"

typedef struct Node
{
 int data;
 Node* next;
};

void insert(Node *s ,Node *a)
{
 Node *p,*q;
 p=NULL;
 q=NULL;
 p=s;
 if(p->next==NULL)  //空链表
 {
   p->next=a;  //a->next已经是NULL
   s->data=s->data+1;
   return;
 }
 q=p;
 p=p->next ;        //链表非空,指向第一个节点
 while((p!=NULL)&&(p->data<a->data))  //找到合适插入节点
 {
  q=p;
  p=p->next ;
 
 }

 if(p==NULL)           //需要插入链尾
 {
  q->next=a;  //a->next已经是NULL
  s->data=s->data+1;
  return;
 
 }
 if(p->data>=a->data)  //需要插入链中间节点
 {
  a->next=p;
  q->next=a;
  s->data=s->data+1;
  return;
 }


}

void main(int argc, char* argv[])
{
 Node* head=NULL;
 Node*temp;
 int n;
 head=(Node*)malloc(sizeof(Node));
 head->data=0;       //链表长度,初始为0
 head->next=NULL;   //链表为空
 int i;
 for(i=0;i<5;i++)
 {  
  
  printf("input a integer/n");
  scanf("%d",&n);
  Node *a=(Node*)malloc(sizeof(Node));
  a->data=n;
  a->next=NULL;
  insert(head,a);
  
 }
   
 printf("The total Node is%d/n",head->data);
    temp=head->next;
    while(temp)
 {
  printf("%d/n",temp->data);
  
  temp=temp->next;
 
 }

 

 

}

posted on 2010-10-29 12:06  IT@民工  阅读(227)  评论(0编辑  收藏  举报

导航