逆置/反转单链表+查找单链表的倒数第k个节点,要求只能遍历一次链表

逆置/反转单链表+查找单链表的倒数第k个节点,要求只能遍历一次链表

#pragma once
#include <stack>
#include <assert.h>
typedef struct NodeList
{
    int _data;
    struct NodeList* _next;

    NodeList(const int& d)
        :_data(d)
        , _next(NULL)
    {}
}Node;
//指针回指
void Reserve(Node *&list)
{

    if (list->_next == NULL || list == NULL)
        return;

        Node*  cur = list->_next;
        Node*  prev = list;
        while (cur)
        {
            Node* pnext = cur->_next;
            cur->_next = prev;
            prev = cur;
            cur = pnext;
        }
        list->_next = NULL;
        list = prev;

}

//栈实现
void Reserve2(Node*& list)
{
    if (list->_next == NULL || list == NULL)
        return;

    stack<Node*> s;

    Node* pcur = list;
    while (pcur->_next)
    {
        s.push(pcur);
        pcur = pcur->_next;
    }

    list = pcur;
    while (!s.empty())
    {
        Node* tmp = s.top();
        pcur->_next = tmp;
        pcur = tmp;
        s.pop();
    }
    pcur->_next = NULL;
}

//查找单链表的倒数第k个节点,要求只能遍历一次链表
Node* FindKToTail(const Node* list, int k)
{
    assert(list && k > 0);
    const Node* fast = list;
    const Node* slow = list;

    while (k--)
    {
        if (fast == NULL)
            return NULL;
        fast = fast->_next;
    }
    while (fast)
    {
        fast = fast->_next;
        slow = slow->_next;
    }

    return (Node*)slow;
}

-实现一个Add函数,让两个数相加,但是不能使用+、-、*、/等四则运算符。ps:也不能用++、–等等

int Add(int num1, int num2)
{
    while (num2 != 0)
    {
        int tmp1 = (num1^num2);
        int tmp2 = (num1&num2) << 1;
        num1 = tmp1;
        num2 = tmp2;
    }
    return num1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值