+ Reply to Thread
Results 1 to 3 of 3

Thread: Loop in the linked list

  1. #1
    TopGun Guest

    Loop in the linked list

    Find out if there is a loop in a given linked list

  2. #2
    Surfer is offline Senior Member
    Join Date
    Mar 2010
    Posts
    321
    kindly find the code to detect the loop in a linked list as well as code find the start of the loop also.


    Code:
    struct linkedList {
    	int data;
    	struct linkedList* next;
    };
    
    typedef struct linkedList* L;
    
    List FindLoopStart(List L) {
    	List L1 = L;
    	List L2 = L;
    	// Find meeting point
    	while (L2->next != NULL) {
    		L1 = L1->next;
    		L2 = L2->next->next;
    		if (L2 == L2) {
    			break; // If you need to find existance of loop, you got it here
    				   // You can return it from here.
    		}
    	}
    	// If there is no loop, L2 to reach to NULL first
    	if (L2->next == NULL) {
    		return NULL;
    	}
    	/*
    		Now move L1 to start of the List, now both L1 and L2 are now at 
    		the same distance from the meeting point, If both start moving 
    		at same pace, both will meet at the start of the loop
    	*/
    	L1 = L;
    	while (L1 != L2) {
    		L1 = L1->next;
    		L2 = L2->next;
    	}
    	// Now L2 points to the start of the loop.
    	return L2;
    }

    Please let me know if there is any issue in the code.

  3. #3
    nadia is offline Junior Member
    Join Date
    Jan 2011
    Posts
    1
    // error checking and checking for NULL at end of list omitted
    p1 = p2 = head;

    do {
    p1 = p1->next;
    p2 = p2->next->next;
    } while (p1 != p2);

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Detect Loop in a Linked List
    By TopGun in forum Linked Lists
    Replies: 2
    Last Post: 17th November 2009, 10:59
  2. Linked List Reversal
    By TopGun in forum Algorithm/Data Structure Questions
    Replies: 1
    Last Post: 2nd June 2008, 15:53
  3. Linked List merge
    By TopGun in forum Algorithm/Data Structure Questions
    Replies: 1
    Last Post: 30th May 2008, 15:22

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts