迅雷2014-difference&&反转链表

本文详细解析了迅雷2014年校招笔试中涉及单链表操作的编程题,包括求集合差集与链表翻转算法实现,提供了完整的代码示例与运行效果,适用于计算机科学与软件工程领域的学习与参考。

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;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值