天天看點

6-3 統計單連結清單元素出現次數 (5分)

本題要求實作一個函數,統計帶頭結點的單連結清單中某個元素出現的次數。

函數接口定義:

L是帶頭結點的單連結清單的頭指針,e是要統計次數的元素值。如果e在單連結清單中存在,函數GetCount傳回其出現的次數;否則,傳回0。

裁判測試程式樣例:

#include <stdio.h>
#include <stdlib.h>

typedef int ElemType;
typedef struct LNode
{
	ElemType data;
	struct LNode *next;
}LNode,*LinkList;

LinkList Create();/* 細節在此不表 */

int GetCount ( LinkList L, ElemType e);

int main()
{
	ElemType e;
	LinkList L = Create();
	scanf("%d",&e);
	printf("%d\n", GetCount(L,e));
	return 0;
}
LinkList Create()
{
	LinkList L,r,p;
	ElemType e;
	L = (LinkList)malloc(sizeof(LNode));
	L->next = NULL;
	r = L;
	scanf("%d",&e);
	while(e!=-1)
	{
		p = (LinkList)malloc(sizeof(LNode));
		p->data = e;
		p->next = r->next;
		r->next = p;
		r = p;
		scanf("%d",&e);
	}
	return L;
}

/* 你的代碼将被嵌在這裡 */
           

輸入樣例1:

2 2 4 2 3 -1
2
           

輸出樣例1:

int GetCount ( LinkList L,ElemType e ){
    int cnt=0;
    while(L->data!=-1&&L->next!=NULL){
        if(L->data == e)
            cnt++;
        L = L->next;
    }
    if(cnt == 0)
        return 0;
    else
        return cnt+1;
}
           

如果你寫成這樣:

int GetCount ( LinkList L,ElemType e ){
    int cnt=0;
    while(L->data!=-1&&L->next!=NULL){
        if(L->data == e)
            cnt++;
        L = L->next;
    }
        return cnt;
}
           

或者這樣:

int GetCount ( LinkList L,ElemType e ){
    int cnt=0;
    while(L->data!=-1&&L->next!=NULL){
        if(L->data == e)
            cnt++;
        L = L->next;
    }
        return cnt+1;
}
           

就會被感受到社會的一頓毒打。别問我怎麼知道的。

……好吧,告訴你。

因為當查無此“e“的時候,你若傳回了cnt+1,結果肯定就不對了啊:同樣的,如果你選擇了傳回cnt,那麼在e存在的情況下就會出錯。

繼續閱讀