您的位置:首页 > 其它

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

2017-07-14 15:32 411 查看

逆置/反转单链表

非递归:

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);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐