剑指offer:调整数组顺序使奇数位于偶数前面&链表中倒数第k个结点&反转链表

13.调整数组顺序使奇数位于偶数前面

/**************************************************************/
/* 题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,
所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。 */
/**************************************************************/

#include <iostream>
#include <vector>
using namespace std;

void reOrderArray(vector<int> &array) {
    if (array.size() == 0 || array.size() == 1)
        return;
    vector<int> array1, array2;
    for (int i = 0; i < array.size(); i++)
    {
        if (array[i] % 2 == 0)
            array2.push_back(array[i]);
        else
            array1.push_back(array[i]);
    }
    array.clear();
    for (int i = 0; i < array1.size(); i++)
    {
        array.push_back(array1[i]);
    }
    for (int i = 0; i < array2.size(); i++)
    {
        array.push_back(array2[i]);
    }
}
int main()
{
    system("pause");
    return 0;
}

14.链表中倒数第k个结点

/**************************************************************/
/* 题目描述
输入一个链表,输出该链表中倒数第k个结点 */
/**************************************************************/

#include <iostream>
#include <vector>
using namespace std;

ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
    if (pListHead == NULL || k < 1)
        return NULL;

    ListNode* pSlow = pListHead, *pFast = pListHead;

    for (int i = 0; i < k; i++)
    {
        if (pFast != NULL)
            pFast = pFast->next;
        else
            return NULL;
    }

    while (pFast != NULL)
    {
        pFast = pFast->next;
        pSlow = pSlow->next;
    }

    return pSlow;
}

15.反转链表

/**************************************************************/
/* 题目描述
输入一个链表,反转链表后,输出新链表的表头。 */
/**************************************************************/

#include <iostream>
#include <vector>
using namespace std;
typedef struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
}ListNode;

ListNode* ReverseList(ListNode* pHead) {
    if (pHead == NULL || pHead->next == NULL)
        return pHead;
    ListNode* pre = pHead, *newHead = pHead, *current = pHead->next;
    while (current != NULL)
    {
        pre->next = current->next;
        current->next = newHead;
        newHead = current;
        current = pre->next;
    }
    return newHead;
}

int main()
{
    ListNode *pNode = new ListNode(1);
    ListNode *p = new ListNode(2);
    pNode->next = p;
    ListNode *p2 = new ListNode(3);
    p->next = p2;
    ListNode *p3 = new ListNode(4);
    p2->next = p3;
    ListNode *head = ReverseList(pNode);
    while (head != NULL)
    {
        cout << head->val << " ";
        head = head->next;
    }
    cout << endl;
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/foreverdongjian/article/details/82190794
今日推荐