Chinaunix首页 | 论坛 | 博客
  • 博客访问: 693284
  • 博文数量: 129
  • 博客积分: 2221
  • 博客等级: 大尉
  • 技术积分: 1620
  • 用 户 组: 普通用户
  • 注册时间: 2011-05-09 11:27
个人简介

do{goodgoodstudy();daydayup();}while(!died)

文章分类

全部博文(129)

文章存档

2012年(26)

2011年(103)

分类: C/C++

2011-05-16 12:25:46

在一个有序单链表中插入值为x的新元素,使该表仍然有序
#include
 
struct link
{    int data;  
      struct link *next;
};
struct link *insert(struct link *head,int n)
{   
    struct link *p=NULL,*q=NULL,*pr=NULL;   
    p=head;   
    q=(struct link *)malloc(sizeof(struct link *));   
    q->data=n;   
    if(p->data>n)   
   {       
        head=q;       
        head->next=p;   
    }   
    else   
    {       
          while(p!=NULL)       
         {           
               if(p->datadata)           
              {             
                   pr=p;               
                   p=p->next;               
                   continue;         
               }           
              else           
               {               
                   pr->next=q;               
                   q->next=p;               
                    break;           
                }       
           }       
       if(p==NULL)      
       {           
             pr->next=q;          
            q->next=NULL;       
        }    
   }   
    return head;
}
 
void show(struct link *head)
{   
         while(head!=NULL)   
         {       
               printf("%d\n",head->data);       
               head=head->next;   
          }   
       printf("\n");
}
 
int main(void)
{   
       struct link *head=NULL;   
       head=(struct link *)malloc(sizeof(struct link *));   
       head->data=7;   
       head->next=NULL;   
       show(head);   
       head=insert(head,4);  
       show(head);   
       head=insert(head,5);  
       show(head);   
       head=insert(head,3);   
       show(head);   
       head=insert(head,6);   
       show(head);   
       head=insert(head,8);   
      show(head);   
      return 0;
}
阅读(7089) | 评论(0) | 转发(1) |
0

上一篇:多好的地方

下一篇:冒泡排序:

给主人留下些什么吧!~~