classSolution {
public:
/**
* @param head: The first node of linked list.
* @return: The new head of reversed linked list.
*/
ListNode *reverse(ListNode *head) {
// write your code hereif(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個節點,要求只能遍歷一次鏈表
classSolution {
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 hereif(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:也不能用++、–
classSolution {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;
intsum=a^b;//進行a+b,但不進位int carry=(a&b)<<1;//看哪一位需要進位,然後左移一位遞歸運算 return aplusb(sum,carry);
}
};