Stack using linked list
In the lists first we have to create a nodde with the fields info and next where info Stores the values in the stack and next is a pointer which points to the next node i.e., it Stores the next node address.
type dy strust stack *stpr; struct stack { int info; stpr next; }; In implementing the stack using linked lists first we create a header and insert the elements to that header.
create_head first create memory for header H=stpr malloc(sizeof(struct stack)); Check for availability of memory If(T==NULL) “out of space” Else Make the next field of the header NULL H->next=NULL;
PUSH(sptr H,INT x)
in the operation push we have to insert the element at the next of the header in linked list. to insert we have to create a node and insert element in the information field and we have to place that node in right position.take header in another pointer variable sptr P=H; create a new node n=(sptr)malloc(sizeof(struct sptr)); if(n==NULL) “out of space” else n->info=x; n->next=H->next; H->next=n;
POP
int pop(sptr H) in this pop(delete) operation we have to delete the element in the node next to header check wether elements exists or not if(H->next==NULL) “no elements in the stack” else store the element in a variable x x=H->next->info delete the node i.e.,change the links in the linked lists P=H->next; H->next=H->next->next; we have to free the memory location by H->next; delete(P);
Here is the code on how to implement stack using linked list using C programming. The Comments will help you get to know how the code works.
Code Starts here
typedef struct node *nptr; struct node { int data; nptr next; }; nptr createhead(void); void display(nptr s); void push(nptr s,int x); int pop(nptr s); nptr createhead() /*Function to create head*/ { nptr H; H=(nptr)malloc(sizeof(struct node)); if(H!=NULL) { H->next=NULL; return(H); } else printf("\n\tOut of Space"); return; } void display(nptr s) /*Function to display the elements*/ { nptr p; p=s; while(p->next!=NULL) { printf("%5d",p->next->data); p=p->next; } } void push(nptr s,int x) /*Function to push the elements*/ { nptr temp; temp=(nptr)malloc(sizeof(struct node)); if(temp==NULL) { printf("Out of Space"); return; } else { temp->data=x; temp->next=s->next; s->next=temp; } } int pop(nptr s) /*Function to pop the elements*/ { nptr temp; int y; if(s->next==NULL) { printf("Underflow on Pop"); return(-1); } else { y=s->next->data; temp=s->next; s->next=temp->next; free(temp); return(y); } }
|
No feedbacks found. Be the first to respond...
|