LC 206. Reverse Linked List

Nilanjan Deb · April 1, 2020

I solved this problem for my academic course COMPUTER PROGRAMMING. Here I used two pointer namely p,q for traversing the linked list. And a temporary pointer to store data of q while traversing. First of all, for corner cases viz. zero and one element return dirctltly head. Then I store the data of head to p and put NULL to the next of head(head->next), Same procedure I follow while traversing firstly I store the data q moves one element faster than p, while traversing firstly I store the data of q in store pointer and move q one forwards then connect the current pointer to the previous pinter and so on Up to q becomes NULL.

This is my CPP solution.

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==NULL || head->next==NULL){
            return head;
        }
        ListNode *p = head ,*q = head->next;
        head->next = NULL;
        while(q!=NULL){
            ListNode *store = q;
            q = q->next;
            store->next = p;
            p = store;
        }
        return p;
    }
};


Dicussion Forum