Linked List

Edge Cases

Case
Problem
Handling

Linked List has single or no elements

Accessing ptr -> next throws an error

if(!A || !(A -> next)) reutrn A

Get Length of a Linked List

int getLength(ListNode* A) {
    int count = 0;
    while(A) {
        count++;
        A = A -> next;
    }
    return count;
}

Get nth Node from Front

Here n[1,A.length]n\in [1, A.length]

ListNode *getNode(ListNode *A, int n) {
    while(--n) 
        A = A -> next;
    
    return A;
}

Get the Last Node of a Linked List

Reverse a Linked List

Get the Middle Element of a Linked List

Last updated