Thread: find middle of a linked list

  1. #1
    Registered User
    Join Date
    Aug 2015
    Posts
    75

    find middle of a linked list

    i tried following function to find middle element of singly linked list, but its not working. Can anyone help please?

    Code:
    findmiddle(node *head){
        node *p1, *p2;
        p1 = head;
        p2 = head;
    
    
        while(p1!=NULL) {
            p1 = p1->next->next;
            p2 = p2->next;
        }
        printf("Middle = %d", p2->data);
    }
    i am using this algorithm

    Traverse linked list using two pointers. Move one pointer by one and other pointer by two. When the fast pointer reaches end slow pointer will reach middle of the linked list.

    UPDATE:

    i added 1 condition in while loop and now its working

    while(p1!=NULL && p1->next!= NULL)
    Last edited by san12345; 01-27-2020 at 08:23 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 02-03-2014, 07:34 AM
  2. adding to middle of linked list
    By johngoodman in forum C Programming
    Replies: 4
    Last Post: 02-18-2013, 12:12 AM
  3. Help with deleting node in the middle of a linked list
    By allplay in forum C Programming
    Replies: 2
    Last Post: 11-11-2006, 11:22 AM
  4. linked list find
    By confuted in forum C++ Programming
    Replies: 7
    Last Post: 07-03-2003, 03:30 PM
  5. Adding To The Middle Of A Linked List
    By LostNotFound in forum C++ Programming
    Replies: 1
    Last Post: 02-23-2003, 06:02 PM

Tags for this Thread