哦莫!刚想开始打卡今天的题,才发现链表忘光了。。。花了点时间复习了下,写了个我估计以后要是再忘了,回来复习也能快速看懂的代码!
#include<stdio.h>
#include<stdlib.h>//链表需要添加的库
typedef int Element;
typedef struct LNode {//定义链表元素
Element data;
struct LNode* next;
} LNode, *LinkedList;//LNode是节点,*LinkedList是指向节点的指针
//销毁链表(free)
void destroy(LinkedList* L) {
do {
LinkedList temp = (LinkedList)malloc(sizeof(LNode));
temp = *L;
*L = (*L)->next;
free(temp);
} while (*L);
}
int main() {
//动态分配内存给head(头指针)
LinkedList head = (LinkedList)malloc(sizeof(LNode));
//如果内存分配失败,则...
if (!head) {
printf("malloc error!\n");
return 0;
}
//创建一个空链表,头指针(head)指向NULL
head->next = NULL;
//初始化该链表
int num = 0;
LinkedList temNode = head;//head是头指针的地址。回忆:int a = 0; int* b = &a;即b指向a!!别搞混咯!
while (1) {
printf("请输入要存入链表的值(输入-1时中止添加):");
scanf_s("%d", &num);
if (num == -1) break;
LinkedList newNode = (LinkedList)malloc(sizeof(LNode));
if (!newNode) {
printf("malloc error!!\n");
//要free一下head
free(&head);
return 0;
}
newNode->data = num;
newNode->next = NULL;
while (temNode->next) temNode = temNode->next;
temNode->next = newNode;
temNode = newNode;
}
//输出链表元素
temNode = head->next;
while(temNode->next){
printf("%d", temNode->data);
temNode = temNode->next;
}
//输出最后一个元素(上面那个循环会遗漏掉最后一个元素)
if (temNode) printf("%d", temNode->data);
//销毁链表
destroy(&head);
return 0;
}