Singly Linked List in C


Stolen Qoute




#include<stdio.h>
#include<string.h>#include<stdlib.h>
{
    int emp_no;
    char emp_name[16];
    int age;
    struct list *next;
}*head = NULL;
void display();
int delete(int );
main() {
    int i, no, ag, data;
    char name[16];
    
    for(i = 0; i <= 2; i++) {
        printf("Enter the Employee no:");
        scanf("%d", &no);
        printf("Enter the Employee name:");
        scanf("%s", name);
        printf("Enter the Employee age:");
        scanf("%d", &ag);
        insert(no, name, ag);
    }
    
    display();
    printf("Enter the element to be deleted");
    scanf("%d", &data);
    /* Lets delete one node */
    delete(data);
    printf("Deleted the data; new list is below\n");
    display();
    printf("DONE\n");
}
void 
insert (int no, char name[], int ag) {
    struct list *tmp = NULL;
    struct list *ptr = NULL;
    struct list *prev =  NULL;
     tmp = (struct list *)malloc(sizeof(struct list));
    strcpy(tmp->emp_name, name);
    tmp->age = ag;
    
    /* Check if the element if it is the first element */
    if (head == NULL) {
        head = tmp;
        tmp->next = NULL;
        return;
    } 
    for (prev = NULL, ptr = head; ptr != NULL; 
         prev = ptr, ptr = ptr->next) {
         /*
          * if new emp no is less than the present add it here
          */
         if (tmp->emp_no < ptr->emp_no) {
             /* Check if list has only one node */
             if (ptr == head) {
                 head = tmp;
                 tmp->next = ptr;
             } else {
                 prev->next = tmp;
                 tmp->next = ptr;
             }
         return;
         }
    }
    /* Add in the End */
    prev->next = tmp;
    tmp->next = NULL;
    return;
}
{
    struct list *cur;
    cur = head;
        printf("EMpty list");
    } else {
        while(cur)
        {
            printf("EMP Number = %d->\n",cur->emp_no);
            cur = cur->next;
        }
        printf("\n");
    }
}
int delete(int data)
{
    struct list *prev, *cur;
   
        if (cur->emp_no == data) {
            if (cur == head) {
                head = cur->next;
                free(cur);
                return (0);
            }
            prev->next = cur->next;
            free(cur);
            return 0;
        }
   }
}
struct list

void insert(int ,char [],int );
int

    tmp->emp_no = no;
void display()
    if (cur == NULL) {
    for (cur = head, prev = NULL; cur; prev = cur, cur = cur->next) {
Post your comments for queries. I hope this will be so helpful...

Comments