## Qual Ex Interview Question

Software Engineer / Developers**Country:**United States

**Interview Type:**In-Person

Yes, there will be no way to look back to know where the element will be. If the input is 40 then its OK. For that the code is as belows:

```
void insertInAscendingOrder(Node node, int insertData) {
while (node.data < insertData && node.next != null) {
node = node.next;
}
if (node.next != null) {
int temp = node.data;
Node newNode = new Node(temp);
newNode.next = node.next;
node.data = insertData;
node.next = newNode;
} else {
if (node.data > insertData) {
int temp = node.data;
Node newNode = new Node(temp);
newNode.next = node.next;
node.data = insertData;
node.next = newNode;
} else {
Node newNode = new Node(insertData);
node.next = newNode;
}
}
}
```

But if the input is 20, then the code will fail and will give the output 10->30->20->50->70

I agree with this opinion as well. If we are only given a pointer to the node with value 50, and no pointers to any node before 50, then by inserting 40 in front of 50 we create a malformed singly linked list. The resulting linked list would have two heads instead of one, which is not allowed according to the traditional definition of linked list.

```
// we start with
// 10->30->50->70->NULL
// curNode is 50, newNode is 40
// first, insert newNode after curNode;
newNode.next = curNode.next;
curNode.next = newNode;
// now we have
// 10->30->50->40->70->NULL
// now swap values of curNode and curNode.next
int tempVal = curNode.value;
curNode.value = curNode.next.value;
curNode.next.value = tempVal;
// now we have
// 10->30->40->50->70->NULL
```

We can also do it by maintaining a prev pointer taking care of the insertion at head.. below is an idea ..

```
node prev = null;
while(newNode.value > Curr.value)
{
prev = curr;
curr = curr.next;
}
if(prev == null)
{
// insertion at head
}
else
{
//insertion at middle or tail
prev.next = newNode;
newNode.next = curr;
}
```

Suppose in the linked list, the first node has a pointer 'first'. and as said in the question, let us assume p is the pointer pointing to node containing value 50. We need to insert node 40 ( let the node be pointer as new) before node 50. So we traverse till we reach a node beofre node 50, and then insert the 'new' node.

Node first = head; //just creating a pointer to move till node before 'p'.

while(first.next != p)

{

first = first.next

} // when this loop is over, you are pointing to a node just ahead of 'p'.

first.next = new;

new.next = p;

Strt with two pointers. One slow and anothoer Fast. Below is the code in Python.

```
class Node:
"""
Basic Node Object
"""
__slots__ = 'elements', 'Next'
def __init__(self, element, Next):
self.element = element
self.Next=Next
class LinkedList(object):
"""
Create a linkedlist object using the Node Object
"""
size = 0 # Let size be the attribute of the LinkedList Class Object
def __init__(self):
"""
Initialize a Head reference of the LinkedList object
"""
self.Head=None
def addElement(self, e):
# Create a newNode Object
newNode = Node(e, None)
if LinkedList.size==0:
self.Head=newNode
else:
newNode.Next=self.Head
self.Head=newNode
LinkedList.size += 1
def displayList(self):
#Create a tempNode and iterate
tempNode = self.Head
while(tempNode):
print "Current element is [%d]"% tempNode.element
tempNode = tempNode.Next
def addElementinOrder(self, e):
# Create a slow pointer and a Fast pointer
# Travel through the list and place the element
# immediately after the element smaller than the given
# element.
# We will also address the edge cases here
slowNode=self.Head
fastNode=self.Head.Next
newNode = Node(e,None)
# Check if the element that is added is less than the head
# Add the element in head
if self.Head.element > e:
self.addElement(e)
# Travel until you reach dead end
else:
while(fastNode):
#stop traversing as soon as you find element larger than target
if fastNode.element > e:
break
else:
# Continue traversing otherwise
slowNode=slowNode.Next
fastNode=fastNode.Next
#Make changes to the node
newNode.Next=fastNode
slowNode.Next=newNode
if __name__== "__main__":
MyLinkedList = LinkedList()
nums = [70, 60, 50, 30, 20, 10]
for n in nums:
print "Inserting num = %d" % n
MyLinkedList.addElement(n)
print "=================================\n"
print "Displaying elements in LinkedList"
MyLinkedList.displayList()
print "=================================\n"
print "The Length of LinkedList is %d" % MyLinkedList.size
print "=================================\n"
print "Inserting 40 in LInkedList"
MyLinkedList.addElementinOrder(40)
print "Displaying elements in LinkedList"
MyLinkedList.displayList()
```

Output:

Inserting num = 70

Inserting num = 60

Inserting num = 50

Inserting num = 30

Inserting num = 20

Inserting num = 10

=================================

Displaying elements in LinkedList

Current element is [10]

Current element is [20]

Current element is [30]

Current element is [50]

Current element is [60]

Current element is [70]

=================================

The Length of LinkedList is 6

=================================

Inserting 40 in LInkedList

Displaying elements in LinkedList

Current element is [10]

Current element is [20]

Current element is [30]

Current element is [40]

Current element is [50]

Current element is [60]

Current element is [70]

```
/**
*
* @param <T>
* @param midNode points to 50
* @param newNode contains 40
*/
public void myAnswer(Node<T> midNode, Node<T> newNode) {
T prevVal = newNode.getValue();
T currValue = null;
while(midNode!=null) {
currValue = midNode.getValue();
midNode.setValue(prevVal);
if(midNode.getNext()!=null) midNode = midNode.getNext();
prevVal = currValue;
}
midNode.setNext(new Node(prevVal));
}
```

```
Node * LinkedList::InsertInOrder(Node *h, Node *p, int data)
{
Node *newNode = new Node(NULL, data);
if(h==NULL || p==NULL)
{
return h;
}
Node *tmp=h, *prev=h;
while(tmp->data<=data)
{
prev=tmp;
tmp=tmp->next;
}
if(tmp==h)
{
newNode->next=tmp;
h=newNode;
}
else
{
prev->next=newNode;
newNode->next=tmp;
}
return h;
}
```

One Possible Solution is this... Code is modifiable

```
public class InsertLinkBeforePointer {
Link<Integer> head = new Link<Integer>(10);
Link<Integer> pointer = null;
public InsertLinkBeforePointer(){
Link<Integer> l1 = new Link<Integer>(20);
Link<Integer> l2 = new Link<Integer>(30);
Link<Integer> l3 = new Link<Integer>(50);
Link<Integer> l4 = new Link<Integer>(60);
head.next = l1;
l1.next = l2;
l2.next = l3;
l3.next = l4;
pointer = l3;
}
public void insertbeforeAsc(int data){
Link<Integer> node = new Link<Integer>(data);
// add the new node where the pointer is pointing..
if(node.data < pointer.data) {
node.next = pointer.next;
pointer.next = node;
// Swap the data in both the nodes..
node.data = pointer.data;
pointer.data = data;
}
else {
while(pointer!=null)
{
if(pointer.data < data)
pointer = pointer.next;
else
{
node.next = pointer.next;
pointer.next = node;
// Swap the data in both the nodes..
node.data = pointer.data;
pointer.data = data;
break;
}
}
}
}
```

```
public class addNodeSpecificIndex extends LinkedList {
public void addNodeMaintainOrder(Node current, int given){
Node fast= current.next;
Node slow= current;
while(fast!=null &&(fast.data<given )){
slow = fast;
fast = fast.next;
}
if(slow.data<given){
Node tmp = new Node(given);
slow.next= tmp;
tmp.next = fast;
}else{
Node tmp = new Node(slow.data);
tmp.next = slow.next;
slow.data = given;
slow.next = tmp;
}
}
public static void main(String[] args){
addNodeSpecificIndex l = new addNodeSpecificIndex();
l.add(0, 5);
l.add(1, 14);
l.add(2, 18);
l.add(3, 23);
l.add(4, 25);
l.add(5, 37);
l.add(6, 44);
System.out.println("After adding elements into the LL \n");
l.display();
Node current = l.getNodeAtIndex(0);
l.addNodeMaintainOrder(current, 31);
l.display();
}
-----------------------------------------------------------------------
Testcase 1:
given pointer to Node: 50
Add value : 40
I/P: 10 30 50 70
O/P : 10 30 40 50 70
-----------------------------------------------------------
Testcase 2:
given pointer to Node: 5
Add value 31
I/P : 5 14 18 23 25 37 44
O/P: 5 14 18 23 25 31 37 44
------------------------------------------------------------------------------
Testcase 3:
given pointer to Node: 44
Add value: 47
I/P: 5 14 18 23 25 37 44
O/P: 5 14 18 23 25 37 44 47
-------------------------------------------------------------------------
Testcase 4:
given pointer to Node: 44
Add value: 40
I/P: 5 14 18 23 25 37 44
O/P: 5 14 18 23 25 37 40 44
```

Say p is the pointer of the node with value being 50, pNew is the pointer of the node with value being 40. Then we can do like this:

- uuuouou May 12, 2014