天天看點

【C語言】指針進階實踐(指針數組和建立單連結清單)

目錄

1、指針數組

2、單連結清單建立

1、指針數組

編寫程式,輸入n(n<10)個字元,輸出其中最長字元串的有效長度。要求自定義函數int max_len(char *s[] , int n),用于計算有n個元素的指針數組n中最長的字元串的長度。 

注意事項:

在使用malloc動态申請記憶體空間時如涉及到多元數組的申請不可一次全部申請,需分次元申請先一級後二級。具體操作請見代碼。

TIPS:指針在VS2010編譯環境中占用4個位元組

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

int max_len(char *s[], int n)
{
	int max, i;
	max = strlen(s[0]);

	for(i = 1; i < n; i ++)
	{
		if(strlen(s[i]) > max)
		{
			max = strlen(s[i]); 
		}
	}
	return max;
}

int main()
{
	int n, i, result;
	char **str;

	printf("n=");
	scanf("%d", &n);
	getchar();

	str = (char **)malloc(n * sizeof(char*)); 
	for(i = 0; i < n; i ++)
	{
		str[i] = (char*)malloc(101 * sizeof(char));	
	}

	for(i = 0; i < n; i ++)
	{
		gets(str[i]);
	}
	result = max_len(str, n);
	printf("%d\n", result);

return 0;
}
           

2、單連結清單建立

1、輸入若幹個學生資訊(包括學号、姓名和成績),輸入學号為0時輸入結束,建立一個單向連結清單,再輸入一個成績值,将成績大于等于該值的學生資訊輸出。

2、輸入若幹個正整數(輸入-1為結束标志),要求按輸入資料的逆序建立一個連結清單,并輸出。

 注意事項:單連結清單的建立分為頭插法和尾插法,使用尾插法建立的單連結清單在資料讀取的時候可按資料輸入的順序讀取,而頭插法建立的單連結清單中資料是逆序存放的。操作具體見代碼。

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

typedef struct stu
{
	int num;
	char name[11];
	int score;
	struct stu *next;
}LNode,*List;

List Head;//頭指針

List CreatList_T()//尾插法
{
	Head = NULL;
	List s;				//結點
	List r;				//尾指針

	int n,sc;
	char na[11];

	s=(List)malloc(sizeof(LNode);
	if(s == NULL)
	{
		printf("記憶體申請失敗\n");
	}
	s ->next = NULL;
	Head = s;	//頭指針指向頭節點
	r = s;
	scanf("%d %s %d", &n, na, &sc);
	
	while(n != 0)
	{
s=(List)malloc(sizeof(LNode));
		if(s == NULL)
		{
			printf("記憶體申請失敗\n");
		}
		s ->num  = n;
		strcpy(s ->name,na);
		s ->score  = sc;

		s ->next = NULL;
		r ->next = s;
		r = s;

		scanf("%d %s", &n, na);
		scanf("%d", &sc);
	}
	return Head;
}

void PrintList(List h,int exp)
{
	h = h ->next ;
	while(h)
	{
		if(h ->score >= exp)
		{
			printf("%d %-6s %d\n", h ->num,h ->name,h ->score );
		}
		h = h ->next ;
	}
}

int main()
{
	List head;
	int exp;

	head = CreatList_T();
	scanf("%d", &exp);
	PrintList(head ,exp);

	return 0;
}
           
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

typedef struct node
{
	int num;
	struct node *next;
}LNode,*List;

List Head;//頭指針

List CreatList_H()//頭插法
{
	Head = NULL;
	List s;				//結點

	int n;

	s = (List)malloc(sizeof(LNode));
	if(s == NULL)
	{
		printf("記憶體申請失敗\n");
	}

	scanf("%d", &n);
	
	while(n != -1)
	{
		s = (List)malloc(sizeof(LNode));
		if(s == NULL)
		{
			printf("記憶體申請失敗\n");
		}
		s ->num  = n;
		s ->next = Head;

		Head = s;
		scanf("%d", &n);
	}
	return Head;
}

void PrintList(List h)
{
	while(h)
	{
		printf("%d ", h ->num);
		h = h ->next ;
	}
	printf("\n");
}

int main()
{
	List head;

	head = CreatList_H();
	PrintList(head);

	return 0;
}
           

繼續閱讀