some algorithmic puzzles, tutorials, interview questions... and stuff...

Thursday, September 03, 2009

How to use the two pointers trick in a linked list

A very simple trick which has multiple uses: finding the middle of a linked list, finding a certain node from the end (e.g. the 3rd node from the end back) or finding if a linked list has loops. I'll just post the code here, using the same structure as in the previous post. It has comments and it's really simple.

Finding the middle of a linked list:

   1:  int findMiddle(node* head) {
   2:      node* middle = head; // the middle will be here
   3:      while (head != 0 && head->next != 0) {
   4:          head = head->next->next; // advance the head by two positions forward
   5:          middle = middle->next; // advance the middle by only one position
   6:      }
   7:      return middle->data;
   8:  }
The solution is O(n) because the algorithm has to go through all the nodes once.

Finding if a linked list has loops (uses almost the same code):

   1:  bool hasLoops(node* head) {
   2:      node* slowPtr = head; //we'll move slower into the list using this pointer
   3:      while (head != 0 && head->next != 0) {
   4:          head = head->next->next; // advance the head by two positions forward
   5:          slowPtr = slowPtr->next; // advance the slowPtr by only one position
   6:          if (head == slowPtr) //these can never become equal unless one pointer loops
   7:              return true;     //back to a previous position, which means there's a loop
   8:      }
   9:      return false;
  10:  }
Again, the solution is O(n) in the worst case because the algorithm has to go through (potentially) all the nodes - it depends on where the loop is.

No comments:

Post a Comment