Cisco Systems Interview Question
Software Engineer / Developers1. Reverse
//!Function reverses an input list
void reverseList(Node*& head){
Node* curr = head;
Node* nxt = head->next;
curr->next = NULL;
while(true){
head = nxt;
if(head->next==NULL){
head->next = curr;
break;
}
nxt = nxt->next;
head->next = curr;
curr = head;
}
}
2. Check if the current value is less for every node and insert
Func division(...) may also include a test if denominator = 2, than whole operation will be just a shift: numerator >>= denominator;
Void insert(Node** head, Node* newNode)
{
Node* curr = *head;
if(*head == null || (*head)->data==newNode->data)
{
newNode->next = (*head);
*head = newNode;
}
while(curr->next!=null && curr->next->data<newNode->data)
curr=crr->next;
newNode->next = curr->next;
curr->next = newNode;
}
ur answer doesnot work if u insert 6 and then 4
// Uses special case code for the head end
void SortedInsert(struct node** headRef, struct node* newNode) {
// Special case for the head end
if (*headRef == NULL || (*headRef)->data >= newNode->data) {
newNode->next = *headRef;
*headRef = newNode;
}
else {
// Locate the node before the point of insertion
struct node* current = *headRef;
while (current->next!=NULL && current->next->data<newNode->data) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
<pre lang="" line="1" title="CodeMonkey86557" class="run-this">void RecursiveReverse(struct node** headRef) {
struct node* first;
struct node* rest;
if (*headRef == NULL) return;
first = *headRef;
rest = first->next;
if (rest == NULL) return;
RecursiveReverse(&rest);
first->next->next = first;
first->next = NULL;
*headRef = rest;
}</pre><pre title="CodeMonkey86557" input="yes">
</pre>
public Node reverseList(Node head)
{
if(head==null)
return null;
else
{
Node temp1,temp2,temp3;
temp1=head;
temp2=head.next;
while(temp2!=null)
{
temp3=temp2.next;
temp2.next=temp1;
temp1=temp2;
temp2=temp3;
}
Head.next=null;
temp2.next=temp1;
return temp2;
// this is not be the best OOdesign.. but answerisnearly the same..since head is a instance variable in a List class, u can say Head= temp2 instead of having a return value.
bool reverse(Node **head)
{
if(*head==NULL) return false;
if(*head->next==NULL) return true;
if(*head->next->next==NULL) {Node *p=*head; *head=*head->next; *head->next=p; return true;}
Node *p1,*p2,*p3;
p1=*head; p2=p1->next; p3=p2->next;
*head->next = NULL;
while(p3)
{
p2->next=p1; p1=p2; p2=p3; p3=p2->next;
}
p2->next=p1; *head = p2;
return true;
}
{
- rayden November 10, 2010Node * ReverseList(Node *head)
{
Node *prev=NULL;
Node *curr=head;
while (curr)
{
curr=curr->next;
head->next=prev;
prev=head;
head=curr;
}
return prev;
}