1 Partition List
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.You should preserve the original relative order of the nodes in each of the two partitions.For example:
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
为了方便对链表第一个节点的操作,这里要用到指向第一个节点的头指针,从头指针开始遍历,我们要用一个变量记录第一次出现节点中元素值大于目标值的位置,继续向后遍历,将小于目标的节点移动变量记录的位置之前。
ListNode* partition(ListNode* head, int x) {
if(head==NULL) return NULL;
ListNode* result=new ListNode(0);
result->next=head;
ListNode* pre=result;
ListNode* premid;
ListNode* cur=head;
ListNode* mid;
bool flag=true; //用来标记找到第一个大于目标值的节点
while(pre->next)
{
if(pre->next->val<x)
{
if(flag)
{
pre=cur;
cur=cur->next;
}
else
{
pre->next=cur->next;
ListNode* reg=cur;
cur=cur->next;
premid->next=reg;
reg->next=mid;
premid=premid->next;
}
}
else
{
if(flag)
{
premid=pre;
mid=pre->next;
flag=false;
pre=cur;
cur=cur->next;
}
else
{
pre=cur;
cur=cur->next;
}
}
}
return result->next;
}
Gray Code
The gray code is a binary numeral system where two successive values differ in only one bit.Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0
01 - 1
11 - 3
10 - 2.
可以从对应的n位二进制码字中直接得到n位格雷码码字,步骤如下:
(1)对n位二进制的码字,从右到左,以0到n-1编号
(2) 如果二进制码字的第i位和i+1位相同,则对应的格雷码的第i位为0,否则为1(当i+1=n时,二进制码字的第n位被认为是0,即第n-1位不变)。用公式表示:
vector<int> grayCode(int n) {
vector<int> result;
int len=1<<n;
for(int i=0;i<len;i++)
{
result.push_back((i>>1)^i);
}
return result;
}
原文地址:http://blog.csdn.net/zhulong890816/article/details/46277163