数据结构:链表常见题目

#include <stdio.h>

BOOL Insert_Last(List *ls, Data data)
{
	if (NULL == ls)
		return ERROR;
	
	Node *node = (Node *)malloc(sizeof(Node)/sizeof(char));
	if (NULL == node)
		return ERROR;
	
	node->data = data;
	node->next = NULL;
	
	Node *tmp = ls->head;         // 头结点
	while (tmp->next)
	{
		tmp = tmp->next;
	}
	
	tmp->next = node;
	
	return TRUE;
}

void Display(List *ls)
{
	if (NULL == ls)
		return;
	
	Node *tmp = ls->head->next;   // 第一个结点
	while (tmp)
	{
		printf ("%-4d", tmp->data);
		tmp = tmp->next;
	}
	printf ("\n");	
}

List *CreateList()//创建链表
{
	List *ls = (List*)malloc(sizeof(List)/sizeof(char));
	if (NULL == ls)
		return NULL;
	
	// 创建头结点
	ls->head = (Node*)malloc(sizeof(Node)/sizeof(char));
	if(NULL == ls->head)
	{
		free(ls);
		return NULL;
	}
	
	ls->head->next = NULL;   // 空链表
	
	return ls;
}

1.寻找第k个结点

int Find_K(List *ls , int k)//找一个不知长度的链表的倒数第K个点
{
	if(NULL == ls)
		return;
	
	int i , count = 0;
	Node *tmp1 = ls->head;
	Node *tmp2 = ls->head;
	
	for(i = 0; i < k; i++)
	{
		tmp1 = tmp1->next;
	}
	
	while(tmp1->next)
	{
		tmp1 = tmp1->next;
		tmp2 = tmp2->next;
		count++;
	}
	
	return count;	
}

2.寻找链表的中点

BOOL Middle_Pos(List *ls)
{
	
	Node *t1=ls->head->next;
	Node *t2=ls->head->next;

	while(t2!=NULL&&t2->next!=NULL)
	{
		t2=t2->next->next;
		t1=t1->next;
	
	}

	printf("%-4d\n",t1->data);
	return TRUE;
}

3.判断有没有环

BOOL Loop(List *ls)
{
	if (NULL == ls)
		return ERROR;
	Node *t1=ls->head;
	Node *t2=ls->head;
	
	while(t2!=NULL&&t1!=NULL)
	{
		t1=t1->next->next;
		t2=t2->next;
		if(t1==t2)
		{
			return TRUE;
		}
	}
	
	return ERROR;
}

4.找到两个链表重合的点

int OverLap(List *ls1 , List *ls2)//找两个链表重合的点
{
	if(NULL == ls1 || NULL == ls2)
		return;
	
	Node *tmp1 = ls1->head;
	Node *tmp2 = ls2->head;
	Node *tmp = ls2->head;
	int pos1 = 1;
	int pos2 = 1;
	
	while(tmp1->next)
	{
		
		tmp1 = tmp1->next;  //第一遍指向ls1的第一个结点
		//printf("tmp1 = %d\n",tmp1->data);	
		
		while(tmp2->next)
		{
			if(tmp1->data == tmp2->next->data)
				return pos1;
			pos2++;
			tmp2 = tmp2->next;
			//printf("pos2 = %d\n",pos2);	
		}
		tmp2 = tmp;
		pos2 = 1;
		pos1++;
		
	}
	
	return pos1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值