dieyushi's Blog

ATOM Rss

leetcode刷题记录8

May 03 2013 , coding

前言

这几天出差,打乱了自己做题的节奏,也只能抽空做几道题来保证做题的感觉了。

题目

Swap Nodes in Pairs

ListNode *swapPairs(ListNode *head) {
    ListNode *curr = head, *tmp = 0, *next = 0, *pre = 0;
    if (curr && curr->next)
        head = curr->next;
    while(curr) {
        if (curr->next == 0) return head;
        next = curr->next;
        if (pre != 0) pre->next = next;
        tmp = next->next;
        next->next = curr;
        curr->next = tmp;
        pre = curr;
        curr = curr->next;
    }
    return head;
}

Remove Duplicates from Sorted Array

int removeDuplicates(int A[], int n) {
    if (n == 0) return 0;
    int start = 0;
    int curr = A[0];

    for (int i=0;i<n;i++){
        if (A[i] != curr) {
            A[start++] = curr;
            curr = A[i];
        }
    }
    A[start++] = curr;
    return start;
}

Remove Element

int removeElement(int A[], int n, int elem) {
    if (n==0) return 0;
    int start = 0;

    for (int i=0;i<n;i++){
        if (A[i] != elem) {
            A[start++] = A[i];
        }
    }
    return start;
}
comments powered by Disqus