高级语言讲义2024软专(仅高级语言部分)

1.实现快速排序,简要分析时间复杂度、空间复杂度。

#include <stdio.h>

void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void printArray(int *arr, int size) {
    for (int i = 0; i < size; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

int partition(int *arr, int low, int high) {
    int pivot = arr[low];
    int i = low + 1;
    int j = high;  
    while (1) {
        while (arr[i] < pivot && i <= high)
            i++;
        while (arr[j] > pivot && j >= low + 1)
            j--;
        if (i >= j)
            break;
        swap(&arr[i], &arr[j]);
    }
    swap(&arr[low], &arr[j]);
    return j; 
}

void quickSort(int *arr, int low, int high) {
    if (low < high) {
        int pivot_index = partition(arr, low, high);
        quickSort(arr, low, pivot_index - 1);
        quickSort(arr, pivot_index + 1, high); 
    }
}

int main() {
    int arr[] = {10, 7, 8, 9, 1, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    printf("Original Array: ");
    printArray(arr, size);
    quickSort(arr, 0, size - 1);
    printf("Sorted Array: ");
    printArray(arr, size);

    return 0;
}

2.int len( char*s),实现该递归函数,计算字符中最后一个单词的长度,若不存在单词{返回0。(字符串由大小写字母、空格组成)

#include <stdio.h>

int strlen(char *s) {
	if(*s=='\0')
		return 0;
	else
		return strlen(s+1)+1;
}

int del(char *s) {
	if(*s==' ')
		return del(s-1)+1;
	return 0;
}

int getlen(char *s) {
	if(*s==' ')
		return 0;
	else
		return getlen(s-1)+1;
}

int main() {
	char str[] = "Hellmo Wiorld";
	printf("%d",getlen(str+strlen(str)-1-del(str+strlen(str)-1)));
	return 0;
}

3.职工信息:工号、姓名、年龄。定义结构体从键盘读入n个职工信息,结点顺序与读入一致。

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

typedef struct node {
	int num;
	char name[20];
	int age;
	struct node *next;
} node;

struct node* create(int n) {
	struct node* head=NULL;
	struct node* p1,*p2;
	for(int i=0; i<n; i++) {
		p1=(struct node *)malloc(sizeof(struct node));
		scanf("%d%s%d",&p1->num,&p1->name,&p1->age);
		if(i==0)
			head=p1;
		else
			p2->next=p1;
		p2=p1;
	}
	p2->next=NULL;
	return head;
}

4.续写,将链表中工号重复的结点删去,并写入" worker.txt"文件中

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

typedef struct node {
	int num;
	char name[20];
	int age;
	struct node *next;
} node;

void removeDuplicates(struct node* head) {
	FILE *file;
	if((file=fopen("worker.txt","w"))==NULL)
		printf("open error");
	if (head == NULL)
		return;
	struct node* current = head;
	while (current->next != NULL) {
		if (current->num == current->next->num) {
			struct node* temp = current->next;
			current->next = temp->next;
			free(temp);
		} else
			current = current->next;
	}
	while(head!=NULL) {
		fprintf(file,"%10s %d %d",head->name,head->age,head->num);
		head=head->next;
	}
	fclose(file);
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值