71.建立正序链表

71.建立正序链表,第1张

71.建立正序链表

请按照输入整数的顺序建立一个带表头节点的链表。已知程序的基本结构如下,请你编写 ins_list 函数。

    #include "stdio.h"    
    #include "stdlib.h"     
    struct node  {   int data;    
        struct node * next;    
    };    
    typedef struct node NODE;    
    typedef struct node * PNODE;    
    void outlist( PNODE );    
    void  ins_list( PNODE h, int num ) ;    
    int main ( ){         
        int num=1;    
        PNODE head;     
        head = (PNODE)malloc( sizeof(NODE) );    
        head->next = NULL;    
        head->data = -1;     
        while ( num!=0 )  {     
            scanf("%d", &num);    
            if ( num!=0 )    
                ins_list( head, num);    
        }   
        outlist( head );    
        return 0;    
    }   
    void  ins_list( PNODE h, int num ){  
        int i;PNODE p;PNODE q;  
        if((h->next)==NULL){  
            p=(PNODE)malloc(sizeof(NODE));  
            h->next = p;  
            p->data=num;  
            p->next = NULL;  
        }else{  
            p=h->next;  
            while((p->next) != NULL){  
                p = p->next;  
            }  
            q=(PNODE)malloc(sizeof(NODE));  
            p->next = q;  
            q->next = NULL;  
            q->data = num;  
        }  
          
    }     
    void outlist( PNODE head )    
    {   PNODE p;    
        p = head->next;    
        while ( p != NULL )    
        {   printf("%dn", p->data);    
            p = p->next;    
        }    
    }  

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5702356.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存