#include<stdio.h>
#include<stdlib.h>

struct Node{
    int data;
    struct Node* prev;
    struct Node* next;
};

struct Node* createNode(int data){
    struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
    newNode->data=data;
    newNode->prev=NULL;
    newNode->next=NULL;
    return newNode;
}
 void printlist(struct Node* head){
     struct Node* temp=head;
     while(temp != NULL){
         printf("%d ", temp->data);
         temp=temp->next;
     }
     printf("\n");
 }
 itn main(){
     int n;
     scanf("%d",&n);
     
     if(n<0){
         printf("Invalid input");
         return 0;
     }
     struct Node *head=NULL, *tail=NULL;
     for(int i=0;i<n;i++){
         int val;
         scanf("%d,&val");
         struct Node* newNode=createNode(val);
         
         if(head==NULL){
             head=tail=newNode;
         }
         else{
             tail->next=newNode;
             newNode->prev=tail;
             tail=newNode;
         }
     }
     int targetID,newID;
     scanf("%d", &targetID);
     scanf("%d", &newID);
     
     if(head !=NULL){
         printlist(head);
 }
 else{
     printf("\n");
     
 }
 struct Node* temp=head;
 while(temp!= NULL && temp->data!=targetID){
     temp=temp->next;
 }
 if(temp==NULL){
     printf("Invalid input");
     return 0;
 }
 struct Node* newNode=createNode(newID);
 newNode->next=temp->next;
 newNode->prev=temp;
 
 if(temp->next !=NULL){
     temp->next->prev=newNode;
     temp->next=newNode;
 }
 printlistt(head);
 
 return 0;
 }