Motorola Interview Question
Android EngineersCountry: Brazil
Interview Type: Phone Interview
class Node{
Node next=null;
int data;
public Node(int data){
this.data=data;
}
if(Node == null) return null;
while(Node != null){
Node n = new Node(data);
n = this.data;
}
add(data);
remove(Node x);
insert(data);
delete(data);
}
public void add(data d){
while(n.next != null){
n.next = this.data;
}
}
public int remove(node x){
while(n.next != null){
if(n.node == x.node){
n.next.node = n.next.next.node;
}
}
}
public void delete(data){
while(n.next != null){
if( n.next.data == data){
n.next.data = n.next.next.data;
}
}
}
public void insert(data){
while(n.next == null){
n.next = data;
}
}
}
public class LinkedList {
private Node firstNode;
private Node lastNode;
private int size = 0;
public void add(Object o) {
Node newNode = new Node(o);
if (firstNode == null) {
firstNode = newNode;
lastNode = newNode;
} else {
lastNode.nextNode = newNode;
lastNode = newNode;
}
size++;
}
public boolean remove(Object o) {
Node nextNode = firstNode;
Node previousNode = null;
while (nextNode != null) {
if (nextNode.o == o) {
removeNode(previousNode, nextNode);
return true;
}
previousNode = nextNode;
nextNode = nextNode.nextNode;
}
return false;
}
private void removeNode(Node previousNode, Node nextNode) {
if (nextNode == firstNode) {
firstNode = nextNode.nextNode;
}
if (nextNode == lastNode) {
lastNode = previousNode;
}
if (previousNode != null) {
previousNode.nextNode = nextNode.nextNode;
}
size--;
}
public boolean insert(int index, Object o) {
if (index < 0 || index > size) {
return false;
}
Node currentNode = null;
int insertIndex = 0;
while (insertIndex <= index) {
if (insertIndex++ == index) {
return insertNode(currentNode, new Node(o));
}
currentNode = currentNode == null ? firstNode : currentNode.nextNode;
}
return false;
}
private boolean insertNode(Node currentNode, Node insertNode) {
if (size == 0 || currentNode == null) {
//add node to the end of list
add(insertNode.o);
return true;
} else {
if (currentNode == lastNode) {
lastNode = insertNode;
}
insertNode.nextNode = currentNode.nextNode;
currentNode.nextNode = insertNode;
size++;
return true;
}
}
private class Node {
private final Object o;
public Node nextNode;
public Node(Object o) {
this.o = o;
}
}
}
{
- Anonymous November 09, 2016}