Pages

Friday, January 31, 2014

REVERSE SINGLY LINKED LIST

typedef struct _listElement {
    int nData;
    struct _listElement* pNext;
} LIST;

/* Reversing A Linked List Recurrsively */
void recurrsivereverse(LIST** pHead) {
    LIST* pCurrent = *pHead;
    LIST* pNext = NULL;
    
    if(pCurrent == NULL) {
        return;
    }
    pNext = pCurrent->pNext;
    recurrsivereverse(&pNext);
    if(pNext)
    {
        pCurrent->pNext->pNext = pCurrent;
        pCurrent->pNext = NULL;
        *pHead = pNext;
    }
    return;
}

/* Reversing A Linked List Iteratively */
void iterativereverse(LIST** pHead) {
    LIST* pCurrent = *pHead;
    LIST* pPrev = NULL;
    LIST* pNext = NULL;

    while(pCurrent) {
        pNext = pCurrent->pNext;
        pCurrent->pNext = pPrev;
        pPrev = pCurrent;
        pCurrent = pNext;
    }
    
    *pHead = pPrev;
    return;
}

No comments: