Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.6 kB
1
Indexable
Never
package BT1_LinkedList;

import java.util.Scanner;

public class Solution {
	static class Node {
		int data;
		Node next;
	}
	 static void print(Node head,int j){
		for (Node p = head.next; p!=null && j-->0 ;p=p.next ){
			
            System.out.print(p.data + " ");
            
        }
		if(head.next==null){
			System.out.print("empty ");
			return;
		}
	}
	 static void insert_head(Node head,int data,int j){
		Node newnode=head;
		while(j-->0 && newnode.next!=null){
			newnode=newnode.next;
		}
		Node p =new Node();
		p.data=data;
		p.next=newnode.next;
		newnode.next =p;
	}
	 static void remove(Node head,int j){
		Node p=head;
		while(j-->0 && p.next!=null){
			p=p.next;
		}
		if(j==-1&& p.next!=null){
			p.next=p.next.next;
		}


	}
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int T=sc.nextInt();
		for(int tc=1;tc<=T;tc++){
			int N=sc.nextInt();
			Node head=new Node();
			head.data=-1;
			head.next=null;
			System.out.print("#"+tc+" ");
			for(int i=0;i<N;i++){
				String s=sc.next();
				//sc.nextLine();
				if(s.charAt(0)=='i'){
					int j=sc.nextInt();
					int data=sc.nextInt();
					insert_head(head, data, j);
				}
				else if(s.charAt(0)=='d'){
					int j=sc.nextInt();
					remove(head,j);
				}
				else if(s.charAt(0)=='p'){
					int j=sc.nextInt();
					print(head,j);
				}
				else if(s.charAt(0)=='r'){
					remove(head,0);
				}
				else {
					int data=sc.nextInt();
					if(s.charAt(0)=='f'){
						insert_head(head, data,0);
					}
					
				}
			}
			System.out.println();
		}
	}
}