55. 链表节点排序

来源:互联网 发布:js种replace方法 编辑:程序博客网 时间:2024/05/13 09:48

请编写函数 sortlist,按照成员data的数值从大到小的顺序建立带有表头结点的链表,且链表中不能有重复的数据。

已知定义如下:
struct node   
{   int data;   
    struct node * next;   
};  
typedef  struct  node  NODE;   
typedef  struct  node  * PNODE;
函数原型 sortlist( PNODE h, int num ) 的参数含义如下: 
       h :单链表的头指针
       num :新输入的需要插入链表中的数据

注意:仅提交自编的sortlist函数,不提交main函数。

预设代码如下

/* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW */#include "stdio.h"   #include "stdlib.h"  struct node   {   int data;       struct node * next;   } ;     typedef  struct  node  NODE;   typedef  struct  node  * PNODE;     int main( )   {   int num=1;       PNODE head;       void sortlist( ), outlist( );     head = ( PNODE )malloc( sizeof(NODE) );       head->next = NULL;       head->data = -1;       while( num!=0 )       {   scanf( "%d", &num ) ;          if( num!=0 )               sortlist( head , num ) ;       }       outlist( head ) ;       return 0;   }   void outlist( PNODE head )   {   PNODE p;       p = head->next;       while( p != NULL )       {   printf("%d\n", p->data);           p = p->next;       }   }   /* This is an example for list. Please programme your code like it. void sortlist( PNODE h, int num ) {   } *//* PRESET CODE END - NEVER TOUCH CODE ABOVE */


下面是我的程序:其实就是有序的插入算法,重复数据不能加入


 /*有序的插入 数据不重复  重复数据不加入*/void sortlist( PNODE h, int num ) {   PNODE t1;PNODE t2,t3;t1 = t2 = h;while((t2=t1->next)!=NULL){if(t2->data == num) break;else if(t2->data < num){t3 = (PNODE)malloc(sizeof(NODE));t3->data = num;t1->next = t3;t3->next = t2;}else{t1=t1->next;}    }if(t2==NULL){t3 = (PNODE)malloc(sizeof(NODE));t3->data = num;t3->next = NULL;t1->next = t3;}} 



原创粉丝点击