小白学算法的感想
今天在B站学习了单链表(头插法,删除,使用递归和迭代的方式反转链表,打印链表),下面是我的代码以及我的一些理解
其次我认为递归就是无限套娃,并且将原来的循环重复的地方单独拿出来封装成一个函数并且设置停止运行的条件,然后在函数中再次调用该函数达到和循环一样的作用 刚刚开始学习,如果有不足的地方请大家指出
#include<stdio.h>
#include <malloc.h>
struct Node
{
int data;
struct Node* next;
};
struct Node* head;
void Insert(int data) {
struct Node* insert = (struct Node*)malloc(sizeof(struct Node));
insert->data = data;
insert->next = head;
head = insert;
}
void InsertByOrder(int data, int location) {
struct Node* insert = (struct Node*)malloc(sizeof(struct Node));
insert->data = data;
if (location == 1) {
insert->data = data;
insert->next = head;
return;
}
struct Node* temp = head;
for (int i = 0; i < location - 2; i++) {
temp = temp->next;
}
insert->next = temp->next;
temp->next = insert;
}
void Delete(int location) {
struct Node* temp1 = head;
if (location == 1) {
head = temp1->next;
free(temp1);
return;
}
for (int i = 0; i < location - 2; i++) {
temp1 = temp1->next;
}
struct Node* temp2 = temp1->next;
temp1->next = temp2->next;
free(temp2);
}
struct Node* Reserve1(struct Node* head) {
struct Node* temp = head;
struct Node* prev = NULL;
struct Node* next = NULL;
while (temp != NULL) {
next = temp->next;
temp->next = prev;
prev = temp;
temp = next;
}
head = prev;
return head;
}
void Reserve2(struct Node* p) {
if (p->next == NULL) {
head = p;
return;
}
Reserve2(p->next);
struct Node* temp1 = p->next;
p->next = NULL;
temp1->next = p;
}
void Print1() {
int count = 0;
struct Node* temp = head;
while (temp != NULL) {
count++;
printf("该链表第%d个元素为:%d\n",count, temp->data);
temp = temp->next;
}
}
void Print2(struct Node* p) {
if (p == NULL) {
printf("\n");
return;
}
printf("%d\n", p->data);
Print2(p->next);
}
int main(void) {
head = NULL;
Insert(0);
Insert(2);
Insert(8);
Insert(5);
InsertByOrder(4, 2);
printf("反转前的链表为:\n");
Print1();
Reserve2(head);
printf("反转后的链表为:\n");
Print1();
Print2(head);
}
|