Untitled
unknown
plain_text
a year ago
3.0 kB
4
Indexable
#include <stdio.h> #include <stdlib.h> struct Node{ int data; struct Node *next; }; struct List { struct Node *head, *tail; }; List l; void init(){ l.head = l.tail = NULL; } void printList(int stt){ struct Node *ptr = l.head; int len = 0; if(ptr == NULL) printf("empty "); else{ while(ptr != NULL){ if(len > stt) { break; } else{ len++; printf("%d ", ptr->data); ptr = ptr->next; } } } } void insertFirst(int key){ struct Node *link = (struct Node*) malloc(sizeof(struct Node)); link->data = key; link->next = l.head; l.head = link; } //void insertLast(int key){ // struct Node *link = (struct Node*) malloc(sizeof(struct Node)); // link->data = key; // link->next = l.tail; // l.tail = link; //} void insert_stt(int key, int stt){ struct Node *ptr = l.head; struct Node *previous = (struct Node*) malloc(sizeof(struct Node)); int len = 0; int check = 0; while(ptr != NULL){ if(len == stt){ check = 1; break; } else{ previous = ptr; len++; ptr = ptr->next; } } if(check == 1){ struct Node *link = (struct Node*) malloc(sizeof(struct Node)); link->data = key; previous->next = link; link->next = ptr; } else { struct Node *pt = l.head; if(pt == NULL) insertFirst(key); else{ struct Node *pre = (struct Node*) malloc(sizeof(struct Node)); while(pt != NULL){ pre = pt; pt = pt->next; } struct Node *link = (struct Node*) malloc(sizeof(struct Node)); link->data = key; pre->next = link; link->next = pt; } } } void deleteFirst(){ struct Node *tempLink = l.head; l.head = l.head->next; tempLink = NULL; } int isEmpty(){ return l.head == NULL; } void deleteStt(int stt){ struct Node* current = l.head; struct Node* previous = NULL; int len = 0; int check = 0; while(current != NULL){ if(len == stt){ check = 1; break; } else { previous = current; current = current->next; len++; } } if(check == 1){ if(current == l.head) l.head = l.head->next; else previous->next = current->next; } } //input char cmline; int j, k, number; int main(){ freopen("input.txt", "r", stdin); int testcase; scanf("%d", &testcase); for(int t=1; t<=testcase; t++){ init(); printf("#%d ", t); //solve scanf("%d", &number); for(int i=0; i<number; i++){ scanf(" %c", &cmline); switch (cmline) { case 'f': scanf("%d", &k); insertFirst(k); break; case 'i': scanf("%d %d", &j, &k); insert_stt(k, j); break; case 'r': if(!isEmpty()){ deleteFirst(); } break; case 'd': scanf("%d", &j); deleteStt(j); break; case 'p': scanf("%d", &j); printList(j); break; default: break; } } printf("\n"); } return 0; }
Editor is loading...
Leave a Comment