Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.0 kB
2
Indexable
Never
#include<iostream>

using namespace std;

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

node pool[30005];
node* head;
int poolCnt;

node* getNode(int val){
	node* newNode=&pool[poolCnt++];
	newNode->data = val;
	newNode->next = 0;
	return newNode;
}

void init(){
	poolCnt=0;
	head=0;
}

int len(){
	int dem=0; node* temp=head;
	while(temp!=NULL){
		dem++;
		temp=temp->next;
	}
	return dem;
}

void putToHead(int val){
	node* newNode=getNode(val);
	newNode->next = head;
	head = newNode;
}

void removeHead(){
	if(head==0) return;
	head=head->next;
}

void insertAt(int pos, int val){
	node* insertNode=getNode(val);
	if(pos==0 || head==NULL) {
		putToHead(val); return;
	}
	node* temp=head;
	for(int i=0;i<=pos-2;i++){
		if(temp->next==NULL){
			temp->next=insertNode;
			return;
		}
		temp=temp->next;
	}	
	insertNode->next=temp->next;
	temp->next = insertNode;
}

void deleteAt(int pos){
	if(pos==0 || head==NULL) {
		removeHead(); return;
	}
	node* temp=head;
	for(int i=0;i<=pos-2;i++){
		temp=temp->next;
		if(temp == NULL) return;
	}
	if(temp->next==NULL) return;
	temp->next = temp->next->next;
}

void print(int pos){
	if(len()==0) cout << "empty ";
	node *temp;
    temp=head;
	int i=0;
    while(temp!=NULL && i<pos) {
        cout << temp->data << " " ;
        temp = temp->next;
		i++;
    }
}

int t,n,x,a,b;
char cmd;

int main(){
	freopen("input.txt","r",stdin);
	cin >> t;
	for(int tc=1;tc<=t;tc++){
		cin >> n;
		init();
		cout << "#" << tc << " ";
		for(int i=0;i<n;i++){
			cin >> cmd;
			switch(cmd){
			case 'r': 
				removeHead();
				break;
			case 'f':
				cin >> x;
				putToHead(x);
				break;
			case 'i':
				cin >> a >> b;
				insertAt(a,b);
				break;
			case 'd':
				cin >> x;
				deleteAt(x);
				break;
			case 'p':
				cin >> x;
				print(x);
				break;
			};
		}
		cout << endl;
	}



	return 0;
}
Leave a Comment