iOS開發進階-算法一

課程: 新浪微博資深大牛全方位剖析 iOS 高級面試

一、字符串反轉

給定字符串 Hello, world, 實現將其反轉。輸出結果dlrow,olleh

思路:使用兩個指針,一個指向字符串首部begin,一個指向字符串尾部end。遍歷過程逐漸交換兩個指針指向的字符,結束條件begin大于end。

void char_reverse(char * cha) {
    // 指向第一個字符
    char *begin = cha;
    // 指向字符串末尾
    char *end = cha + strlen(cha) - 1;
    while (begin < end) {
        // 交換字符,同時移動指針
        char temp = *begin;
        *(begin++) = *end;
        *(end--) = temp;
    }
}

二、鏈表反轉

思路:頭插法實現鏈表反轉。定義一個新的head指針作為鏈表的頭部指針,定義一個P指針遍歷鏈表,將每次遍歷到的元素插入到head指針后。

代碼示例:

// 鏈表反轉
struct Node * reverseList(struct Node *head) {
    // 定義變量指針,初始化為頭結點
    struct Node *p = head;
    // 反轉后的鏈表頭
    struct Node *newH = NULL;
    while (p != NULL) {
        // 記錄下一個結點
        struct Node *temp = p -> next;
        p->next = newH;
        // 更新鏈表頭部為當前節點
        newH = p;
        // 移動P指針
        p = temp;
    }
    return newH;
}
// 構建一個鏈表
struct Node * constructList(void) {
    // 頭結點
    struct Node *head = NULL;
    // 記錄當前節點
    struct Node *cur = NULL;
    
    for (int i = 0; i < 5; i++) {
        struct Node *node = malloc(sizeof(struct Node));
        node->data = i;
        
        if (head == NULL) {
            head = node;
        } else {
            cur->next = node;
        }
        cur = node;
    }
    return head;
}
// 打印鏈表
void printList(struct Node *head) {
    struct Node *temp = head;
    while (temp != NULL) {
        printf("node is %d \n", temp->data);
        temp = temp->next;
    }
}

測試代碼:

    struct Node *head = constructList();
    printList(head);
    printf("---------\n");
    struct Node *newHead = reverseList(head);
    printList(newHead);

輸出結果:
node is 0
node is 1
node is 2
node is 3
node is 4


node is 4
node is 3
node is 2
node is 1
node is 0

三、有序數組合并

如何實現兩個有序數組合并成新的有序數組。

思路:兩個指針分別指向兩個有序數組,比較指針所指向的數據大小,將較小的先插入到新的數組中,最后剩余的那個數組合并到新數組末尾。

示例代碼:

// 將有序數組a和b的值合并到一個數組result中,且仍保持有序
void mergeSortedArray(int a[], int aLen, int b[], int bLen, int result[]) {
    int p = 0; // a 數組標記
    int q = 0; // b 數組標記
    int i = 0; // 當前存儲位標記
    // 任意數組結束
    while (p < aLen && q < bLen) {
        // 將較小的按個插入到新數組中
        if (a[p] <= b[q]) {
            result[i] = a[p];
            p++;
        } else {
            result[i] = b[q];
            q++;
        }
        i++;
    }
    // a數組還有剩余
    while (p < aLen) {
        result[i] = a[p++];
        i++;
    }
    // b數組有剩余
    while (q < bLen) {
        result[i] = b[q++];
        i++;
    }
}

測試代碼:

void array_mergeSortedTest() {
    int a[5] = {1, 3, 4, 5, 9};
    int b[6] = {2, 8, 10, 23, 32, 43};
    int result[11];
    mergeSortedArray(a, 5, b, 6, result);
    printf("merge result is ");
    for (int i = 0; i < 11; i++) {
        printf("%d ", result[i]);
    }
}

輸出結果:
merge result is 1 2 3 4 5 8 9 10 23 32 43

示例代碼倉庫地址:Algorithm

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容