Advertisement
hamaXD

lab 6-2 nosure

Oct 31st, 2017
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.09 KB | None | 0 0
  1. #include<stdio.h>
  2. struct listnode {
  3.   int data;
  4.   struct listnode *next;
  5. };
  6.  
  7. typedef struct listnode LN;
  8.  
  9. void insert_at_front(LN **hptr, int d);
  10. void print(LN *head);
  11. int sum(LN *head);
  12. LN *find_tail(LN *head);
  13.  
  14. int main(){
  15.   LN *head;
  16.   head = NULL;
  17.   int d;
  18.   printf("Enter data: ");
  19.   do{
  20.     scanf("%d", &d);
  21.     if(d > 0){
  22.         insert_at_back(&head,d);
  23.     }
  24.   }while(d > 0);
  25.     printf("=");
  26.     print(head);
  27.     printf("\n=%d", sum(head));
  28.   return 0;
  29. }
  30.  
  31. void insert_at_back(LN **hptr, int d){
  32.     LN *new_node = (LN*)malloc(sizeof(LN));
  33.     LN *tail;
  34.     new_node->data=d;
  35.     new_node->next=NULL;
  36.     tail=find_tail(*hptr);
  37.     if(tail==NULL)
  38.         *hptr=new_node;
  39.     else
  40.         tail->next=new_node;
  41.    
  42. }
  43. void print(LN *head){
  44.         while(head!=NULL){
  45.             printf("%d ",head->data);
  46.             head=head->next;
  47.           }
  48. }
  49.  
  50. int sum(LN *head){
  51.         int num=0;
  52.         while(head!=NULL){
  53.             num=num+head->data;
  54.             head=head->next;
  55.         }
  56.         return num;
  57. }
  58. LN *find_tail(LN *head){
  59.     LN *tail;
  60.     if(head==NULL)
  61.         return NULL;
  62.     tail=head;
  63.     while(tail->next!=NULL){
  64.         tail=tail->next;
  65.     }
  66.     return tail;   
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement