每日一刷——逆置单链表&&查找倒数第k个节点&&Add函数

来源:互联网 发布:后二计算软件 编辑:程序博客网 时间:2024/06/11 09:42

1.【基础题】–逆置/反转单链表+查找单链表的倒数第k个节点,要求只能遍历一次链表

ListNode *reverse(ListNode *head) {        // write your code here     ListNode* newhead = NULL;     ListNode* cur = head;    while (cur)    {        ListNode* tmp = cur;        cur = cur->next;        tmp->next = newhead;        newhead = tmp;    }    return newhead;    }
 ListNode *nthToLast(ListNode *head, int n) {        // write your code here        ListNode* pfast=head;        ListNode* pslow=head;        while(n--)        {            pfast=pfast->next;        }        while(pfast)        {             pfast=pfast->next;             pslow=pslow->next;        }        return pslow;    }

2.【附加题】–实现一个Add函数,让两个数相加,但是不能使用+、-、*、/等四则运算符。ps:也不能用++、–等等
这里写图片描述

int Add(int n1,int n2){int sum=0;sum=((n1^n2)+(n1&n2)<<1);return sum;} 
原创粉丝点击