Advertisement
hamaXD

lab 6- 1 แบบกลับ

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