鏈家筆試算法題

1 給定一個數組,將奇數排在偶數前面
思路:類似於快排的思想

#include<iostream>
#include<stdio.h>
#include<memory.h>

using namespace std;

void exchange(int a[], int n)
{
    int low = 0, high = n-1;
    while(low < high)
    {
        while(low < high && a[low] % 2 == 1) low++;
        while(low < high && a[high] % 2 == 0) high--;
        swap(a[low],a[high]);
    }
}

2 刪除有序鏈表中的重複元素
代碼如下:

#include<iostream>
#include<stdio.h>
#include<memory.h>

using namespace std;

struct LinkList
{
    int val;
    LinkList * next;
    LinkList(int v):val(v) {}
};

void removeDup(LinkList * head)
{
    LinkList *pre, * cur;
    if(head == nullptr) return ;
    pre = head; cur = pre->next;
    while(cur)
    {
        if(cur->val == pre->val)
        {
            cur = cur->next;
            pre->next = cur;
        }
        else
        {
            pre = cur;
            cur = cur->next;
        }
    }
}
//測試
int main()
{
    int a[] = {1,1,2,3,3,4};
    LinkList *head = nullptr, *p = nullptr;
    for(int i = 0; i < 6; i++)
    {
        if(head == nullptr)
        {
            head = p= new LinkList(a[i]);
            p->next = nullptr;
        }
        else
        {
            p->next = new LinkList(a[i]);
            p = p->next;
            p->next = nullptr;
        }
    }
    p = head;
    while(p)
    {
        cout<<p->val<<" ";
        p = p->next;
    }
    cout<<endl;
    removeDup(head);
    p = head;
    while(p)
    {
        cout<<p->val<<" ";
        p = p->next;
    }

    return 0;
}

3 大數乘法
4 編輯距離

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章