## Amazon Interview Question

Quality Assurance Engineers**Country:**India

**Interview Type:**In-Person

```
public void addElements(int k) {
DoubleSidedLnkedList node = new DoubleSidedLnkedList(k);
if (head == null) {
head = node;
temp = node;
} else if (k == 0) {
while (temp.previous != null) {
temp=temp.previous;
}
node.next = temp;
temp.previous=node;
}
else{
while (temp.next != null) {
temp=temp.next;
}
node.previous = temp;
temp.next=node;
}
}
```

You can try and solve this using linked list implementation. If input is one you add it at the end of the linked list, if the input is zero you add it at the start. Each time user inputs something, just print the whole linked list.

```
public Node buildList(int input, Node head) {
Node temp = new Node();
Node tempHead = head;
if (input == null || head == null)
return null;
if (head.value == null){ // first element
head.value = input;
return head; // all done!
}
if (input == 1) // add to the end of the list
while(tempHead.next != null) // iterate to the end of the list
tempHead = tempHead.next;
temp.value = input;
tempHead.next = temp
else if (input == 0){ // add to beginning
temp.value = input;
temp.next = head;
tempHead = temp; // assign this as the new head
}
return tempHead;
```

}

{

{

{#include<stdio.h>

#include<conio.h>

int a[50],b[50],count=0;

void zero(int ,int );

void display();

void zero(int p,int q)

{

int i;

for(i=q;i>=0;i--)

{

b[i+1]=b[i];

}

b[0]=p;

}

void display(int i)

{

int j;

for(j=0;j<=i;j++)

printf("%d",b[j]);

}

void main()

{

int i,j;

clrscr();

i=0;

while(i<50)

{

scanf("%d",&a[i]);

if(a[i]==0)

{ zero(a[i],i);

count++;

}

else if(a[i]==1)

{ b[count]=a[i];

count++;

}

else

break;

printf("\t");

display(i);

printf("\n");

i++;

}

getch();

exit (1);

}

}

}

}

static String s ="";

public static void main(String args[])

{

Scanner in = new Scanner(System.in);

while (in.hasNext())

{

String str = in.nextLine();

if(str.equals("1") || str.equals("0"))

{

String s1 = testmethod(str);

System.out.println("s= "+s1);

}

else

return; // break; can also be used here.

}

}

public static String testmethod(String args)

{

if(args.equals("0"))

{

s = args+s;

}

else if(args.equals("1"))

{

s = s+args;

}

return s;

}

Just keep a count of the number of zeros and the number of ones, since they can't be intermingled. No data structure even required.

- nilkn January 23, 2014