在一些大的公司尤其是大的互联网公司面试的时候,链表的一些趣味算法是经常出现。
下面就来是两个常见的面试题:
1.判断一个单链表是不是存在环。
#include<iostream>
using namespace std;
struct node
{
int element;
node *next;
};
//创建单链表链表
node *create_list(int n)
{
if(n <= 0)
{
return NULL;
}
node *head = NULL;
node *p = new node;
if(p == NULL)
{
return NULL;
}
head = p;
while(--n)
{
node *q = new node;
if(q == NULL)
{
return NULL;
}
p->next = q;
p = q;
}
p->next = NULL;
return head;
}
//创建循环单链表链表
node *create_loop_list(int n)
{
if(n <= 0)
{
return NULL;
}
node *head = NULL;
node *p = new node;
if(p == NULL)
{
return NULL;
}
head = p;
while(--n)
{
node *q = new node;
if(q == NULL)
{
return NULL;
}
p->next = q;
p = q;
}
p->next = head;
return head;
}
bool has_roll(const node* head)
{
const node* p = head;
const node* q = head->next;
while(q != NULL && q->next != NULL && p != q)
{
p = p->next;
q = q->next->next;
}
if(p == q)
{
return true;
}
else
{
return false;
}
}
int main()
{
int n = 0;
cin>>n;
node *head = create_list(n);
if(has_roll(head))
{
cout<<"有环"<<endl;
}
else
{
cout<<"无环"<<endl;
}
head = create_loop_list(n);
if(has_roll(head))
{
cout<<"有环"<<endl;
}
else
{
cout<<"无环"<<endl;
}
return 0;
}
2.有N个小孩围成一圈,从第K个儿童从1开始依次报数,直到数到M,数到M的同学出列,下一个同学再从1开始报数到M,依次循环,直到最后剩下一个同学,问最后一个同学是谁。
#include<iostream>
using namespace std;
struct node
{
int num;
node *next;
};
//创建循环单链表链表
node *create_loop_list(int n)
{
if(n <= 0)
{
return NULL;
}
node *head = NULL;
node *p = new node;
if(p == NULL)
{
return NULL;
}
head = p;
int i = 1;
p->num = i;
while(--n)
{
node *q = new node;
q->num = ++i;
if(q == NULL)
{
return NULL;
}
p->next = q;
p = q;
}
p->next = head;
return head;
}
//删除从头结点起的第m个结点
node *delete_node(node* head, int m)
{
node *p = head;
node *t = p;
m = m - 1;
while(m--)
{
t = p;
p = p->next;
}
t->next = p->next;
head = t->next;
delete p;
return head;
}
node *last_one(int N, int K, int M)
{
node *head = create_loop_list(N);
while(--K)
{
head = head->next;
}
while(head != head->next)
{
head = delete_node(head, M);
}
return head;
}
int main()
{
int N = 0;
int K = 0;
int M = 0;
cin>>N>>K>>M;
node *last = last_one(N, K, M);
cout<<last->num<<endl;
return 0;
}