Thursday, November 5, 2009

Stack in Data Structures -- C++

# include
# include

struct node{
    int x;
    struct node *next;
};

typedef struct node nd;

// Inserting elements in ascending order
void insert_list(nd **head,int num)
{
  nd *p, *temp;

  temp = (nd*) malloc(sizeof(nd));
  temp->x = num;
  p = *head;
 
  /* insert at beginning*/
   *head = temp;
     temp->next = p;
  printf("\n\nPUSH: Element is added\n\n");
 
}
//Display contents of the linked list

void display_list(nd **head)
{
  nd *p;
  p=*head;
  while (p!=NULL)
  {
     printf("%d\n",p->x);
     p=p->next;
  }
}

void delete_list(nd **head)
{
  nd *p,*temp;

  /*check if list is empty*/
  p = *head;
  if (head == NULL)
     { printf("The list is empty");
        return;
     }
  else
    /* delete the first node*/
     {temp = *head;
      *head = p->next;
      free(temp);
      printf("\n\nPOP: Element is Deleted\n\n");
     }
 

 
}

void main()
{
    int choice,num;
    nd *list=NULL;

   
 do
 {
  printf("Choose an operation:\n");
  printf("1 - Add an element(in stack)  \n");
  printf("2 - Delete an element(in stack)  \n");
  printf("3 - Display the elements  \n");
  printf("4 - Exit\n");
  printf("Enter your choice(1-4) :");
  scanf("%i",&choice);
  system("cls");
  if (choice == 1){
        printf("Enter item to be inserted :");
        scanf("%d",&num);
        insert_list(&list,num);
     }
     else if (choice == 2){
   
        delete_list(&list);
      }
     else if (choice == 3)
        display_list(&list);
    }
 while (choice!= 4);
};

Labels: , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home