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

来源:互联网 发布:活动致辞知乎 编辑:程序博客网 时间:2024/06/09 21:24

逆置/反转单链表+查找单链表的倒数第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;}
阅读全文
0 0
原创粉丝点击