个人主页
个人简介
作者是一个来自河源的大三在校生,以下笔记都是作者自学之路的一些浅薄经验,如有错误请指正,将来会不断的完善笔记,帮助更多的Java爱好者入门。
C语言数据结构与算法
BF和KMP算法
#include <stdio.h>
int slen(char* s)
{
int i = 0;
if (s == NULL) {
return 0;
}
else {
while (s[i] != '\0')
{
i++;
}
return i;
}
}
//BF
int* bf(char* str,char *ptr)
{
int i=0, j=0;
int index = 0;
int strlen = slen(str);
int ptrlen = slen(ptr);
while (i<strlen&&j<ptrlen)
{
if (str[i]==ptr[j]) {
i++;
j++;
}
else {
index++;
i = index;
j = 0;
}
}
if (j == ptrlen) {
return i-j;
}
else {
return -1;
}
}
//kmp
int* kmp(char* haystack, char* needle)
{
int i = 0, j = 0;
int strlen = slen(haystack);
int ptrlen = slen(needle);
while (i < strlen && j < ptrlen)
{
if (haystack[i] == needle[j]) {
i++;
j++;
}
else {
i = i-j+1;
j = 0;
}
}
if (j == ptrlen) {
return i - j;
}
else {
return -1;
}
}
int main(void)
{
char *str= "hello";
char* ptr = "ll";
//int res=bf(str, ptr);
int res = kmp(str, ptr);
printf("%d \n",res);
return 0;
}
循环链表
#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0
//C语言实现循环链表
//链表结点
typedef struct Node {
int data;
struct Node* next;
} node;
typedef struct Node* linklist;
void initList(linklist head)
{
printf("初始化循环链表......\n");
if (head == NULL) {
head = (node*)malloc(sizeof(node));
}
head->data = 0;
head->next = head; //初始化给head的指针指向自己
}
//插入(尾插法)
void tailAddNode(linklist head,int data) {
node* p = (node*)malloc(sizeof(node));
p->next = head;
node* newNode = (node*)malloc(sizeof(node));
newNode->data = data;
while (true) {
if (p->next->next == head) { //当前p->next就是尾
p->next->next = newNode;
newNode->next = head;
head->data++;
printf("插入结点成功......\n");
break;
}
else {
p->next = p->next->next;
}
}
}
//删除
void deleteNode(linklist head,int index)
{
node* p = (node*)malloc(sizeof(node));
p->next = head;
int cur = 0;
//int in = index % (head->data); //in是取模后的下标
while (true)
{
if ((cur+1)==index) //此时下一个结点就是我们要删除的结点
{
node* temp = p->next->next;
p->next->next = p->next->next->next;
head->data--;
free(temp);
printf("删除结点成功......\n");
break;
}
else {
p->next = p->next->next;
cur++;
}
}
}
void printList(linklist head)
{
node* p = (node*)malloc(sizeof(node));
p->next = head->next;
while (true) {
if (p->next->next == head) {
printf("%d ", p->next->data);
printf("进入循环-> %d ", p->next->next->next->data);
break;
}
else {
printf("%d ",p->next->data);
p->next = p->next->next;
}
}
}
int main(void)
{
linklist head = (node*)malloc(sizeof(node));
initList(head);
tailAddNode(head, 15);
tailAddNode(head, 22);
tailAddNode(head, 33);
printList(head);
deleteNode(head,3);
printList(head);
return 0;
}
斐波那契和阶乘
#include <stdio.h>
#include <stdlib.h>
//递归题 easy
//1.斐波那契数列
int fib(int n) {
if (n == 0)
{
return 0;
}
if (n == 1)
{
return 1;
}
return fib(n - 1) + fib(n - 2);
}
//2.阶乘
int jiecheng(int n)
{
if (n==0||n == 1)
{
return 1;
}
else {
return n * jiecheng(n - 1);
}
}
int main(void)
{
int res=jiecheng(10);
printf("%d\n",res);
return 0;
}