您的位置:首页 > 理论基础 > 数据结构算法

我思故我在系列—数据结构面试12,13题(题目搜集整理者V_JULY_V,非常感谢!!)

2011-10-15 20:42 330 查看
[b]目标的实质不会有多大区别,生活中没有哪个地方能够对信心和努力的组合免疫。

[/b]

——摘自奥格.曼狄诺《羊皮卷



第12 题

题目:求1+2+…+n,


要求不能使用乘除法、for、while、if、else、switch、case 等关键字以及条件判断语句(A?B:C)。

解题思路:用其他方法代替递归,循环等,让相同的代码执行N次;

方法1:

#include <iostream>

using namespace std;

class Temp

{

public:

Temp() { ++N; Sum += N; }

//static int Reset() {++N;Sum+=N;}

static int GetSum() { return Sum; }

private:

static int N; /*注意静态成员,普通成员,普通变量在做++,--的不同效果,(详见扫雷项目)*/

static int Sum;

};

int Temp::N = 0;

int Temp::Sum = 0;

int solution1_Sum(int n)

{

// Temp::Reset();

Temp *a = new Temp
; /*new 出n 个数组。,每次NEW一个对象,调用一次构造函数*/

delete[] a;

a = NULL;

return Temp::GetSum();

}

int main()

{

cout<<solution1_Sum(100)<<endl;

return 0;

}

#include <iostream>

using namespace std;:

class A

{

public:

virtual int Sum (int n) { return 0; }

};

A* Array[2];/*实现多态的两个要点:基类指针数组与虚函数*/

class B: public A

{

public:

/*对n 连续做两次反运算,即!!n,那么非零的n 转换为true,0转换为false,调用基类的函数。*/

virtual int Sum (int n) { return Array[!!n]->Sum(n-1)+n; }

};

int solution2_Sum(int n)

{

A a;

B b;

Array[0] = &a;

Array[1] = &b;

int value = Array[1]->Sum(n);

//利用虚函数的特性,当Array[1]为0时,即Array[0] = &a; 执行A::Sum,

//当Array[1]不为0时, 即Array[1] = &b; 执行B::Sum。

return value;

}

int main()

{

cout<<solution2_Sum(100)<<endl;

return 0;

}

/*第13题:

题目:

输入一个单向链表,输出该链表中倒数第k 个结点,

链表的倒数第0个结点为链表的尾指针。

*/


#include <iostream>

#include <stdio.h>

#include <stdlib.h>

using namespace std;

typedef struct ListNode

{

int data;

ListNode* next;

}*Linklist;

Linklist create_sLink()

{

int input;

Linklist Head=NULL;

Linklist pcur=NULL;

Linklist qend=NULL;

// Head= new ListNode;

Head=(Linklist)malloc(sizeof(ListNode));

Head->next=NULL;

cout<<"please input data:";

cin>>input;

while(input!=0)

{

// pcur=new ListNode;

pcur=(Linklist)malloc(sizeof(ListNode));

pcur->data=input;

pcur->next=NULL;

if(Head->next==NULL)

{

Head->next=pcur;

}

else

{

qend->next=pcur;

}

qend=pcur;

cout<<"please input data:";

cin>>input;

}

return Head;

}

ListNode* fun(Linklist head,int k)/*找到最后第K个节点*/

{

Linklist Pre=NULL,Nex=NULL;

Pre= Nex = head;

for(int i=0;i<=k-1;i++)/*移动K个位置*/

{

Nex=Nex->next;

}

while(Nex!=NULL)/*Pre与Nex相差K个结点*/

{

Nex=Nex->next;

Pre=Pre->next;

}

return Pre;

}

void free_sLink(Linklist Head)

{

Linklist f;

while( Head->next!=NULL )

{

f=Head;

Head=Head->next;

free(f);

f=NULL;

}

free(Head);

Head=NULL;

}

int main()

{

Linklist H;

H=create_sLink();

cout<<"---------------"<<endl;

cout<<fun(H,2)->data<<endl;

free_sLink(H);

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐