一天6道题之第四题:链表组件

题目描述:
在这里插入图片描述
题目解读:
如果当前结点在列表G中,并且下一个结点不在列表G中,我们就找到了一个组件,就将res+1

所以这一道题其实是很简单的,首先写主函数:

int main(){
	ListNode *head=createByTail();
	vector<int> G;
	int m,data,res;
	cin>>m;
	for(int i=0;i<m;i++){
		cin>>data;
		G.push_back(data);
	}
	res=Solution().numComponents(head,G);
	cout<<res<<endl;
	return 0;
}

我们可以看到在这里用到了vector容器,这是前面三道题不曾用到的,所以先来简单的了解一下vector:
vector(向量)是一个封装了动态大小数组的顺序容器。跟任意其他类型的容器一样,它能够存放各种类型的对象。关于vector的更多细节可以看官方文档,在这里只要知道几种常见的函数就可以了,噢对了,记得加头文件:

#include<vector>
vector<int> G;
int data;
G.push_back(data); //在数组的最后添加一个数据
G.pop_back(); //去掉数组的最后一个数据
G.size();//返回向量中元素的个数

所以这道题最主要的就是写出numComponents(head,G)这个函数,那么我们先来回顾一下,这个函数是让干嘛的——求组件的个数,换句话说,如果链表当前结点在G中并且下一个结点不在G中,res+1,最后返回res。循环条件是head一直往后遍历直到head==NULL;
所以可以写出以下代码:

int numComponents(ListNode *head,vector<int> &G){
	
	int res=0;
	while(head){
		if(isExist(head,G) && !isExist(head->next,G){
			res+=1;
		}
		head=head->next;
	}
	return res;
}

bool isExist(ListNode *head,vector<int> &G){
	if(head==NULL) return false;
	for(int i=0;i<G.size();i++){
		if(G[i]==head->val){
			return true;
		}
	}
	return false;
}

看完上面的代码我们可以发现最重要的就是这个isExist()函数,这个函数的功能就是判断当前结点是否在容器G中,是怎么判断的呢?首先如果是空链表,直接返回false完事,如果链表不为空,就拿出head即当前结点的数据值,同时遍历G中的每一个元素,然后去比较,如果有一样的就说明当前结点是在G中的,就返回true,然后再利用这个函数去判断当前结点的下一个结点的数据值是否在G中,如果不在,同时为true就res+1;否则直接返回res。

完整代码:

#include<iostream>
#include<vector>
using namespace std;
//题目解析: 如果当前结点在列表G中,并且下一个结点不在列表G中,我们就找到了一个组件,就将res+1
// 
struct ListNode{
	int val;
	ListNode *next;
};

ListNode *createByTail(){
	ListNode *head;
	ListNode *p;
	ListNode *tail;
	int len;
	int n=0,num;
	cin>>len;
	head=NULL;
	while(n<len && cin>>num){
		p=new ListNode;
		p->val=num,
		p->next=NULL;
		n=n+1;
		if(n==1){
			head=p;
		}
		else{
			tail->next=p;
		}
		tail=p;
	} 
	return head;
} 


class Solution{
	public:
		int numComponents(ListNode *head,vector<int> &G){
			int flag=0;
			while(head){
				//if(当前结点在G中并且下一个结点不在G中){
				if(isExist(head,G) && !isExist(head->next,G)){
				
					flag+=1;
				} 
				head=head->next;
			} 
			return flag;
		}
		
		bool isExist(ListNode *head,vector<int> &G){
			if(head==NULL){
				return false;//如果链表为空,则直接返回0
			}
			for(int i=0;i<G.size();i++){
				if(G[i]==head->val){
					return true;
				}
			}
			return false;
		}
		
};


int main(){
	vector<int> G;
	int m,data,res;
	ListNode *head=createByTail();
	cin>>m;
	for(int i=0;i<m;i++){
		cin>>data;
		G.push_back(data);
	}
	res=Solution().numComponents(head,G);
	cout<<res<<endl;
	return 0;
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值