2011年1月8日 星期六

Linked List (3)

Sum up values of all items in a Linked List (items are integers)
int Sum(Node *head)
{
    if (head == NULL)
        return 0;
    else
        return head->data + Sum(head->next);
}

Print all items in a Linked List
void Print1(Node *head)
{
    if (head == NULL) // Special Case! head is null!
        return;
    else {
        printf("%d ", head->data);
        Print1(head->next);
    }
}

Reversely print all items
void Print(Node *head)
{
    if (head == NULL)
        return;
    else {
        Print(head->next);        // Recursively call itself, 
        printf("%d ", head->data);// so last one is printed first.

    }
}

Find the last Mth item: Ex.find the last 2th in 1->4->5->2->9->0->3->Null => 0
Node* Find_Mth_Last(Node **head, int M)
{
    Node *p1, *p2;
    p1 = *head;
 
    while (M >= 0 && p1 != NULL) { // p1 goes to Mth first
        p1 = p1->next;             
        M -= 1;
    }
 
    if (M != -1) {  // if we can find out, M == -1, not M == 0
        printf("can't find Mth, because its shorter than M!");
        return NULL;
    }
 
    p2 = *head;         // p2 points to 1st
    while (p1 != NULL) {// when p1 to the end, p2 points to Mth
        p1 = p1->next;    
        p2 = p2->next;
    }
 
    return p2;
}

沒有留言:

張貼留言