0% found this document useful (0 votes)
119 views

Linked List Based Algo's

The document discusses several questions related to linked lists in C programming. It provides code snippets to reverse a singly linked list iteratively and recursively, delete a node given a pointer, sort a linked list, detect loops, find the middle node, and more. It also discusses approaches to solve problems like reversing a linked list without pointers and using binary search on a linked list.

Uploaded by

Jidav
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views

Linked List Based Algo's

The document discusses several questions related to linked lists in C programming. It provides code snippets to reverse a singly linked list iteratively and recursively, delete a node given a pointer, sort a linked list, detect loops, find the middle node, and more. It also discusses approaches to solve problems like reversing a linked list without pointers and using binary search on a linked list.

Uploaded by

Jidav
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

How do you reverse a singly linked list? How do you reverse a doubly linked list?

Write a C program to do the same.

#include <stdio.h> #include <stdlib.h> struct linkedList{ int element; struct linkedList *next; }; typedef struct linkedList* List; List reverseList(List L) { List tmp, previous=NULL; while(L){ tmp = L->next; L->next = previous; previous = L; L = tmp; } L = previous; return L; } Resurcive Method to reverse the list. List recursiveReverse(List L) { List first, rest; if(!L) return NULL; first = L; rest = L->next; if(!rest) return NULL; rest = recursiveReverse(rest); first->next->next = first; first->next = NULL; L=rest; return L; }
Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?

#include <stdio.h> #include <stdlib.h> struct linkedList{ int element; struct linkedList* next; }; typedef struct linkedList* List; void deleteNode(List Node) { List tmp; if(Node){ // If current node is not NULL tmp = node->next; // take backup of next Node Node->element = Node->next->element; // replace current node

element with next Node element Node->next = Node->next->next; // change next pointer to next to next free(tmp); // free the next Node which was taken backup } return; }
How do you sort a linked list? Write a C program to sort a linked list.

This is a very popular interview question, which most people go wrong. The ideal solution to this problem is to keep the linked list sorted as you build it. Another question on this website teaches you how to insert elements into a linked list in the sorted order. This really saves a lot of time which would have been required to sort it. However, you need to Get That Job.... Method1 (Usual method) The general idea is to decide upon a sorting algorithm (say bubble sort). Then, one needs to come up with different scenarios to swap two nodes in the linked list when they are not in the required order. The different scenarios would be something like

1. When the nodes being compared are first node. 2. When the nodes being compared are first node 3. When the nodes being compared are node. 4. When the nodes being compared are node. Note : We can also use Merge Sort.

not adjacent and one of them is the not adjacent and none of them is the adjacent and one of them is the first adjacent and none of them is the first

How do you reverse a linked list without using any C pointers?

One way is to reverse the data in the nodes without changing the pointers themselves. One can also create a new linked list which is the reverse of the original linked list. A simple C program can do that for you. Please note that you would still use the "next" pointer fields to traverse through the linked list (So in effect, you are using the pointers, but you are not changing them when reversing the linked list).
How would you detect a loop in a linked list? Write a C program to detect a loop in a linked list.

/* Start two pointers at the head of the list Loop infinitely If the fast pointer reaches a NULL pointer Return that the list is NULL terminated If the fast pointer moves onto or over the slow pointer Return that there is a cycle Advances the slow pointer one node Advances the fast pointer two node */ #include <stdio.h> #include <stdlib.h> struct linkedList{ int element; struct linkedList* next; };

typedef struct linkedList* List;

/* Takes a pointer to the head of a linked list and determines if the list ends in a cycle or is NULL terminated */ int DetermineTermination(List *head) { List *fast, *slow; fast = slow = head; while(1) { if(!fast || !fast->next) return 0; else if(fast == slow || fast ->next == slow) return 1; // Loop detected else{ slow = slow->next; fast = fast->next->next; } } }
How do you find the middle of a linked list? Write a C program to return the middle of a linked list.

Another popular interview question Here are a few C program snippets to give you an idea of the possible solutions. Method1 (Uses one slow pointer and one fast pointer) #include<stdio.h> #include<ctype.h> typedef struct node { int value; struct node *next; struct node *prev; }mynode ; // // // // // This function uses one slow and one fast pointer to get to the middle of the LL. The slow pointer is advanced only by one node and the fast pointer is advanced by two nodes!

// Here p moves one step, where as q moves two steps, when q reaches end, p // will be at the middle of the linked list. void getTheMiddle(mynode *head) { mynode *p = head; mynode *q = head; if(q!=NULL) { while((q->next)!=NULL && (q->next->next)!=NULL) { p=(p!=(mynode *)NULL?p->next:(mynode *)NULL); q=(q!=(mynode *)NULL?q->next:(mynode *)NULL); q=(q!=(mynode *)NULL?q->next:(mynode *)NULL); } printf("The middle element is [%d]",p->value);

} } Method2(Uses a counter) #include<stdio.h> #include<ctype.h> typedef struct node { int value; struct node *next; struct node *prev; }mynode ; mynode *getTheMiddle(mynode *head) { mynode *middle = (mynode *)NULL; int i; for(i=1; head!=(mynode *)NULL; head=head->next,i++) { if(i==1) middle=head; else if ((i%2)==1) middle=middle->next; } return middle; } In a similar way, we can find the 1/3 th node of linked list by changing (i%2==1) to (i%3==1) and in the same way we can find nth node of list by changing (i%2==1) to (i%n==1) but make sure ur (n<=i).
If you are using C language to implement the heterogeneous linked list, what pointer type will you use?

The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type.
Write a C program to free the nodes of a linked list.

Before looking at the answer, try writing a simple C program (with a for loop) to do this. Quite a few people get this wrong. This is the wrong way to do it struct list *listptr, *nextptr; for(listptr = head; listptr != NULL; listptr = listptr->next) { free(listptr); } If you are thinking why the above piece of code is wrong, note that once you free the listptr node, you cannot do something like listptr = listptr>next!. Since listptr is already freed, using it to get listptr->next is illegal and can cause unpredictable results! This is the right way to do it struct list *listptr, *nextptr; for(listptr = head; listptr != NULL; listptr = nextptr) {

nextptr = listptr->next; free(listptr); } head = NULL; After doing this, make sure you also set the head pointer to NULL!
Can we do a Binary search on a linked list?

The answer is ofcourse, you can write a C program to do this. But, the question is, do you really think it will be as efficient as a C program which does a binary search on an array? Think hard, real hard. Do you know what exactly makes the binary search on an array so fast and efficient? Its the ability to access any element in the array in constant time. This is what makes it so fast. You can get to the middle of the array just by saying array[middle]!. Now, can you do the same with a linked list? The answer is No. You will have to write your own, possibly inefficient algorithm to get the value of the middle node of a linked list. In a linked list, you loosse the ability to get the value of any node in a constant time. One solution to the inefficiency of getting the middle of the linked list during a binary search is to have the first node contain one additional pointer that points to the node in the middle. Decide at the first node if you need to check the first or the second half of the linked list. Continue doing that with each half-list.
Write a C program to return the nth node from the end of a linked list.

Suppose one needs to get to the 6th node from the end in this LL. First, just keep on incrementing the first pointer (ptr1) till the number of increments cross n (which is 6 in this case) STEP 1 STEP 2 : : 1(ptr1,ptr2) -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 1(ptr2) -> 2 -> 3 -> 4 -> 5 -> 6(ptr1) -> 7 -> 8 -> 9 -> 10

Now, start the second pointer (ptr2) and keep on incrementing it till the first pointer (ptr1) reaches the end of the LL. STEP 3 : 1 -> 2 -> 3 -> 4(ptr2) -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 (ptr1)

So here you have!, the 6th node from the end pointed to by ptr2! struct node { int data; struct node *next; }mynode; mynode * nthNode(mynode *head, int n /*pass 0 for last node*/) { mynode *ptr1,*ptr2; int count; if(!head) { return(NULL); } ptr1 = head; ptr2 = head; count = 0;

while(count < n) { count++; if((ptr1=ptr1->next)==NULL) { //Length of the linked list less than n. Error. return(NULL); } } while((ptr1=ptr1->next)!=NULL) { ptr2=ptr2->next; } return(ptr2); }
How would you find out if one of the pointers in a linked list is corrupted or not?

This is a really good interview question. The reason is that linked lists are used in a wide variety of scenarios and being able to detect and correct pointer corruptions might be a very valuable tool. For example, data blocks associated with files in a file system are usually stored as linked lists. Each data block points to the next data block. A single corrupt pointer can cause the entire file to be lost! Discover and fix bugs when they corrupt the linked list and not when effect becomes visible in some other part of the program. Perform frequent consistency checks (to see if the linked list is indeed holding the data that you inserted into it). It is good programming practice to set the pointer value to NULL immediately after freeing the memory pointed at by the pointer. This will help in debugging, because it will tell you that the object was freed somewhere beforehand. Keep track of how many objects are pointing to a object using reference counts if required. Use a good debugger to see how the datastructures are getting corrupted and trace down the problem. Debuggers like ddd on linux and memory profilers like Purify, Electric fence are good starting points. These tools should help you track down heap corruption issues easily. Avoid global variables when traversing and manipulating linked lists. Imagine what would happen if a function which is only supposed to traverse a linked list using a global head pointer accidently sets the head pointer to NULL!. Its a good idea to check the addNode() and the deleteNode() routines and test them for all types of scenarios. This should include tests for inserting/deleting nodes at the front/middle/end of the linked list, working with an empty linked list, running out of memory when using malloc() when allocating memory for new nodes, writing through NULL pointers, writing more data into the node fields then they can hold (resulting in corrupting the (probably adjacent) "prev" and "next" pointer fields), make sure bug fixes and enhancements to the linked list code are reviewed and well tested (a lot of bugs come from quick and dirty bug fixing), log and handle all possible errors (this will help you a lot while debugging), add multiple levels of logging so that you can dig through the logs. The list is endless... Each node can have an extra field associated with it. This field indicates the number of nodes after this node in the linked list. This extra field needs to be kept up-to-date when we inserte or delete nodes in the linked list (It might become slightly complicated when insertion or deletion

happens not at end, but anywhere in the linked list). Then, if for any node, p->field > 0 and p->next == NULL, it surely points to a pointer corruption. You could also keep the count of the total number of nodes in a linked list and use it to check if the list is indeed having those many nodes or not.

The problem in detecting such pointer corruptions in C is that its only the programmer who knows that the pointer is corrupted. The program has no way of knowing that something is wrong. So the best way to fix these errors is check your logic and test your code to the maximum possible extent. I am not aware of ways in C to recover the lost nodes of a corrupted linked list. C does not track pointers so there is no good way to know if an arbitrary pointer has been corrupted or not. The platform may have a library service that checks if a pointer points to valid memory (for instance on Win32 there is a IsBadReadPtr, IsBadWritePtr API.) If you detect a cycle in the link list, it's definitely bad. If it's a doubly linked list you can verify, pNode->Next->Prev == pNode.

I have a hunch that interviewers who ask this question are probably hinting at something called Smart Pointers in C++. Smart pointers are particularly useful in the face of exceptions as they ensure proper destruction of dynamically allocated objects. They can also be used to keep track of dynamically allocated objects shared by multiple owners. This topic is out of scope here, but you can find lots of material on the Internet for Smart Pointers.
Write a C program to remove duplicates from a sorted linked list?

As the linked list is sorted, we can start from the beginning of the list and compare adjacent nodes. When adjacent nodes are the same, remove the second one. There's a tricky case where the node after the next node needs to be noted before the deletion. // Remove duplicates from a sorted list void RemoveDuplicates(struct node* head) { struct node* current = head; if (current == NULL) return; // do nothing if the list is empty // Compare current node with next node while(current->next!=NULL) { if (current->data == current->next->data) { struct node* nextNext = current->next->next; free(current->next); current->next = nextNext; } else { current = current->next; // only advance if no deletion } } }
How can I search for data in a linked list?

The only way to search a linked list is with a linear search, because the only way a linked list?s members can be accessed is sequentially. Sometimes it is quicker to take the data from a linked list and store it in a different data structure so that searches can be more efficient.

You might also like