逆置、翻轉鏈表/查找單鏈表的倒數第k個節點/A+B不使用四則運算++ -- 等

逆置/反轉單鏈表

  • 非遞歸:
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);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章