struct Node
{
Node *next;
int value;
Node(int val):value(val),next(NULL){ }
};
void Reverse(Node *&phead)
{
if(phead == NULL || phead->next == NULL)
return ;
Node *pcur = phead->next;
Node *pre = phead;
while(pcur)
{
Node *pnext = pcur->next;
pcur->next = pre;
pre = pcur;
pcur = pnext;
}
phead->next = NULL;
phead = pre;
}
void Reverse2(Node *&phead)
{
if(phead == NULL || phead->next == NULL)
return ;
stack<Node*> s;
Node *pcur = phead;
while(pcur->next)
{
s.push(pcur);
pcur= pcur->next;
}
phead = pcur;
while(!s.empty())
{
Node *ptemp = s.top();
pcur->next = ptemp;
pcur = ptemp;
s.pop();
}
pcur->next = NULL;
}
void Reverse3( Node *&phead)
{
if(phead == NULL || phead->next == NULL)
return ;
Node *pNewHead = phead;
Node *pcur = phead->next;
pNewHead->next = NULL;
while(pcur)
{
Node *pnext = pcur->next;
pcur->next = pre;
pre = pcur;
pcur = pnext;
}
phead = pNewHead;
}
struct ListNode
{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL) { }
};
ListNode *FindKthToTail(const ListNode *pListHead, int k)
{
assert(pListHead && k > 0);
const ListNode *pFast = pListHead;
while(k--)
{
if(pFast == NULL)
return NULL;
pFast = pFast->next;
}
const ListNode *pSlow = pListHead;
while(pFast)
{
pFast = pFast->next;
pSlow = pSlow->next;
}
return (ListNode*)pSlow;
}
实现一个Add函数,让两个数相加,但是不能使用+、-、*、/等四则运算符。ps:也不能用++、--等等
int Add(int num1, int num2)
{
while(num2 != 0)
{
int temp1 = (num1^num2);
int temp2 = (num1&num2)<<1;
num1 = temp1;
num2 = temp2;
}
return num1;
}