9月9日,迅雷2014校招笔试编程题:
已知集合A和B的元素分别用不含头结点的单链表存储,函数difference()用于求解集合A与B的差集,并将结果保存在集合A的单链表中。例如,若集合A={5,10,20,15,25,30},集合B={5,15,35,25},完成计算后A={10,20,30}。
链表结点的结构类型定义如下:
struct node {
int elem;
node * next;
};#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef int bool;
#define true 1
#define false 0
typedef struct node node;
struct node {
int elem;
node * next;
};
node * new_node(int elm, node * next)
{
node * ptr_new = (node*)malloc(sizeof(node));
ptr_new->elem = elm;
ptr_new->next = next;
return ptr_new;
}
node * insert_head(node* L, int elm)
{
if(L == 0)
return new_node(elm, NULL);
return new_node(elm, L);
}
void print_list(node* L)
{
node * ptr = L;
while(ptr != NULL)
{
printf("%d ", ptr->elem);
ptr = ptr->next;
}
printf("\n");
}
void difference(node ** LA , node* LB)
{
/* 保存LA头结点 */
node * ptr_a_head = *LA;
node * ptr_a = *LA;
node * ptr_a_before = NULL;
node * ptr_b = LB;
node * tmp = NULL;
bool is_existed = false;
int elm = 0;
while(ptr_a != NULL)
{
elm = ptr_a->elem;
// 如果elm存在于链表LB中,则删除
ptr_b = LB;
is_existed = false;
while(ptr_b != NULL)
{
if(ptr_b->elem == elm)
is_existed = true;
ptr_b = ptr_b->next;
}
// 删除,不需要更新ptr_a_before
if(is_existed)
{
// 如果是头结点
if(ptr_a_head == ptr_a)
{
tmp = ptr_a;
ptr_a = ptr_a->next;
// 更新头结点
ptr_a_head = ptr_a;
free(tmp);
}
else
{
ptr_a_before->next = ptr_a->next;
tmp = ptr_a;
ptr_a = ptr_a->next;
free(tmp);
}
}
else
{
ptr_a_before = ptr_a;
ptr_a = ptr_a->next;
}
}
*LA = ptr_a_head;
}
int main(int c, char * v[])
{
int i = 0;
int A[] = {5,10,20,15,25,30};
int B[] = {5,15,35,25};
node * root_a = NULL;
node * root_b = NULL;
for(i = 0; i < sizeof(A)/sizeof(int); i++){
root_a = insert_head(root_a, A[i]);
}
print_list(root_a);
for(i = 0; i < sizeof(B)/sizeof(int); i++){
root_b = insert_head(root_b, B[i]);
}
print_list(root_b);
difference(&root_a, root_b);
print_list(root_a);
}
链表翻转。给出一个链表和一个数k,比如链表1→2→3→4→5→6,k=2,则翻转后2→1→4→3→6→5,若k=3,翻转后3→2→1→6→5→4,若k=4,翻转后4→3→2→1→5→6,用程序实现
void reverse_k(node**head, int k)
{
node * ptr_fore;
node * ptr;
node * tmp = 0;
int cnt = 0;
k--;
if(*head != 0){
ptr_fore = *head;
ptr = (*head)->next;
}
while(ptr != 0 && cnt < k)
{
tmp = ptr->next;
ptr->next = ptr_fore;
ptr_fore = ptr;
ptr = tmp;
cnt++;
}
(*head)->next = ptr;
*head = ptr_fore;
return;
}
本文详细解析了迅雷2014年校招笔试中涉及单链表操作的编程题,包括求集合差集与链表翻转算法实现,提供了完整的代码示例与运行效果,适用于计算机科学与软件工程领域的学习与参考。
4256

被折叠的 条评论
为什么被折叠?



