逆置、翻转链表/查找单链表的倒数第k个节点/A+B不使用四则运算++ -- 等

来源:互联网 发布:项目进度跟踪软件 编辑:程序博客网 时间:2024/06/08 18:36

逆置/反转单链表

  • 非递归:
class Solution {public:    /**     * @param head: The first node of linked list.     * @return: The new head of reversed linked list.     */    ListNode *reverse(ListNode *head) {        // write your code here        if(head==NULL||head->next==NULL)            return head;        ListNode* newhead=head;        ListNode* cur=head->next;        newhead->next=NULL;        while(cur)        {            head=cur->next;            cur->next=newhead;            newhead=cur;            cur=head;        }        return newhead;    }};

查找单链表的倒数第k个节点,要求只能遍历一次链表

class Solution {public:    /**     * @param head: The first node of linked list.     * @param n: An integer.     * @return: Nth to last node of a singly linked list.      */    ListNode *nthToLast(ListNode *head, int n) {        // write your code here        if(head==NULL)            return head;        ListNode* fast=head,*cur=head;        while(n--&&fast)//快指针先走n步慢指针在走,另外要记得防止n大于链表节点个数        {            fast=fast->next;        }        if(n>0&&fast!=NULL)            return NULL;        while(fast)        {            fast=fast->next;            cur=cur->next;        }        return cur;    }

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

class Solution {public:    /*     * @param a: The first integer     * @param b: The second integer     * @return: The sum of a and b     */    int aplusb(int a, int b) {        // write your code here, try to do it without arithmetic operators.        if(a==0)            return b;        if(b==0)            return a;        int sum=a^b;//进行a+b,但不进位        int carry=(a&b)<<1;//看哪一位需要进位,然后左移一位递归运算          return aplusb(sum,carry);    }};
阅读全文
0 0
原创粉丝点击