Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Abhilash I abhilashi@students.iiit.ac.in
Basics
In C struct node{ int data; struct node * next; } In C++ struct node{ int data; node * next; }
Operations
Allocation of Memory
struct node *nn = (struct node *)malloc(sizeof(struct node)); //c node *nn = new node; //c++ style
Insertion Deletion
Variants
Structural Variants 1. Single Linked List
Variants : operational
Stack LIFO
Queue FIFO
Problem #1
Find the maximum/mininum elements of linked list ? Trivial isn't it. A way to write the solution. node* findMaximum(node *head){ node * returnValue=head; while(head!=NULL){ if (head->data > returnValue->data){ returnValue=head; } head=head->next; } return reuturnValue; } Variable Naming/ Style of code is important
Problem #2
Find Union/Intersection of two linked lists ? Typically you would have to write a function that returns a new list, with specified criteria Write it down
Problem #3
Reverse a given linked list Hottest problem that is always asked 1. Iterative solution 2. Recursive solution Constraints (da routine ones :P ) 1. O(1) Space 2. O(n) Time
Iterative Solution
void reverse(struct node **x){ struct node *q,*r,*temp; r=*x; q=NULL; while(r!=NULL){ temp=q; q=r; r=r->next; q->next=temp; } *x=p; }
Recursive Solution
node* reverse(node** head , node* cur){ if(cur->next == NULL) { *head = cur; } else{ (reverse(head,cur->next))->next = cur; cur->next = NULL; } return cur; }
Depends on the problem at hand. Example: Moving one pointer as slow as Tortoise, and moving another as fast as Hare. Also known as Floyd's cycle detection algorithm Next 4 problems can be solved using this trick
Problem #4
Find the kth element from the end of linked list ? Constraints 1. O(1) space 2. O(n) time
Problem #6
Find the center of Linked List ? Constraint : Without using integer variables
Problem #7
Find whether a linked list has a cycle or not ? Possible approches 1. By storing the addresses all the elements already seen ? 2. By destructing the linked list ? What if we don't have auxilary storage and also do it without destructing the list ? Hint: Apply the intuition from previous slide Extension: Find the node at which the loop starts ?
Stacks
Implement a stack using 2 queues efficiently Reverse a stack inplace Implement 3 stacks in an array You are given a black box datastructure which does insertion and extract min in O(1) time. give an efficient implementation for extract max using the operations supported by it. What is the black box ? How to achieve this ?
cont
We are given with two arrays A and B..each of size N... elements of array contains either 1 or 0... we have to find such an interval (p,q)(inclusive) such that the sum of all the elements of A (between this interval) and sum of all elements of B (between this interval ) is equal... i.e. a[p]+a[p+1]....+a[q]= b[p]+b[p+1]....+b[q]