Popular Posts

Showing posts with label Linked List. Show all posts
Showing posts with label Linked List. Show all posts

Monday, August 1, 2011

Problem:
You have two numbers represented by a linked list, where each node contains a single digit   The digits are stored in reverse order, such that the 1’s digit is at the head of
the list   Write a function that adds the two numbers and returns the sum as a linked
list
EXAMPLE
Input: (3 -> 1 -> 5) + (5 -> 9 -> 2)
Output: 8 -> 0 -> 8
Solution:
  1. Have pointer on each head of the two list
  2. Add the data of two nodes along with carry.
  3. create new result node and put the value, SUM % 10
  4. assign SUM / 10 to carry
  5. Repeat until any one list exhausts.
  6. Then add the carry to the node, repeat till end of list
Complexity: O(n) where n>=m, m and n are length of two lists
Code:



Problem:
  Write code to remove duplicates from an unsorted linked list
Solution:
  1. Have two pointers ptr1 and ptr2.
  2. For each node ptr1 visits check from head [head  to node before ptr1] whether that data is already present.
  3. If so, remove the ptr1 node.
  4. return the new list without any duplicates
Complexity: O(n^2)
Code:





Sunday, July 31, 2011

Problem:
There are 2 link lists merging at some node. Find the node, where these 2 lists merge.


Solution:
             

  1. Point both the heads with temp1 and temp2 pointers.
  2. Move both pointers one step at a time.
  3. Repeat step 2 until temp1 or temp2 reaches the last node.
  4. Make a pointer P1 to point the head of longest list and pointer P2 to point the head of another list.
  5. Move the temp pointer of longest list and another pointer from its list head one position at a time until temp reaches the last node.
  6. Now we have two pointers with equal numbers of nodes.
  7. move two pointers one at a time until they both meet.
  8. return the merge node.

Complexity: O(m+n)
Code:



Thursday, July 28, 2011

Reverse a Linked List recursively



Thursday, July 14, 2011

Delete alternate nodes of a Linked List

Problem:
Given a Singly Linked List, starting from the second node delete all alternate nodes of it. For example, if the given linked list is 1->2->3->4->5 then your function should convert it to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3.
Solution:
  •   Have two pointers p and q
  • Initially p points head and q points to link of p i.e 2nd node (if exists).
  • Make the link of p to point to link of q
  • free q
  • move p to its link i.e next node
  • move q to next node of p
  • loop until p or q becomes NULL.

Complexity: O(n)
Code:

List *deletealternative(List *head)
{
    if(head==NULL)
        return NULL;
    List *p=head;
    List *q=p->link;
    
    while(p!=NULL && q!=NULL)
    {
        p->link=q->link;
        free(q);
        p=p->link;
        if(p!=NULL)
            q=p->link;
    }
    return head;
}