Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define TYPE int
- typedef struct Node{
- TYPE data;
- struct Node *next;
- }Node;
- void reset(Node **lsHead);
- int isEmpty(Node **lsHead);
- void addToStart(Node **lsHead,TYPE val);
- void addToEnd(Node **lsHead,TYPE val);
- TYPE popStart(Node **lsHead);
- TYPE popEnd(Node **lsHead);
- int main(){
- system("clear");
- Node *ls = NULL; reset(&ls);
- addToStart(&ls,5);
- addToStart(&ls,4);
- addToEnd(&ls,6);
- printf("pop end: %d\n", popEnd(&ls));
- printf("pop start: %d\n", popStart(&ls));
- printf("pop end: %d\n", popEnd(&ls));
- return 0;
- }
- void reset(Node **lsHead){ *lsHead = NULL; }
- int isEmpty(Node **lsHead){ return !*lsHead; }
- void addToStart(Node **lsHead,TYPE val){
- Node *node = (Node*) malloc(sizeof(Node));
- node->data = val;
- node->next = *lsHead;
- *lsHead = node;
- }
- void addToEnd(Node **lsHead,TYPE val){
- Node *node = (Node*) malloc(sizeof(Node));
- node->data = val; node->next = NULL;
- if(isEmpty(lsHead))
- *lsHead = node;
- else{
- Node *last = *lsHead;
- while(last->next) last = last->next; // getting the latest node
- last->next = node;
- }
- }
- TYPE popStart(Node **lsHead){
- if(!isEmpty(lsHead)){
- TYPE val = (*lsHead)->data;
- Node *start = *lsHead;
- free(start);
- *lsHead = (*lsHead)->next;
- return val;
- }
- return 1<<31;
- }
- TYPE popEnd(Node **lsHead){
- if(!isEmpty(lsHead)){
- Node *preLast = *lsHead;
- if(preLast->next && preLast->next->next)
- while((preLast->next)->next)
- preLast = preLast->next;
- Node * last = preLast->next;
- if(!last){
- // last node in list
- TYPE val = preLast->data;
- free(preLast);
- reset(lsHead);
- return val;
- }else{
- // not last node
- TYPE val = last->data;
- preLast->next = NULL;
- free(last);
- return val;
- }
- }
- return 1<<31;
- }
Advertisement
Add Comment
Please, Sign In to add comment