在用c语言的函数时,要记住: c语言函数内部的值, 只能在通过返回值来获取.
#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
typedef int ElemType;
typedef struct Node {
ElemType date;
struct Node* next;
}Node, LinkList;
LinkList* InitList(LinkList* L) {
L = (LinkList *) malloc( sizeof(Node));
L->next = NULL;
return L;
}
int ListInsert_back(LinkList* L, Node* node) {
Node* last = NULL;
if (!L || !node)return ERROR;
last = L;
while (last->next) last = last->next;
node->next = NULL;
last->next = node;
return OK;
}
int LinkInsert(LinkList* L, int i, int e) {
if (!L) return ERROR;
int j = 0;
LinkList* p, * s;
p = L;
while (p && j < i - 1) {
p = p->next;
j++;
}
if (!p || j > i - 1) {
return ERROR;
}
s = (LinkList*)malloc(sizeof(Node));
s->date = e;
s->next = p->next;
p->next = s;
return OK;
free (s);
}
int Link_FindElem(LinkList* L, int e) {
LinkList* p;
p = L->next;
int index = 1;
if (!L || !L->next) {
index = 0;
return ERROR;
}
while (p && p->date != e) {
p = p->next;
index++;
}
if (!p) {
index = 0;
return ERROR;
}
return index;
}
int LinkDelete(LinkList* L, int i) {
LinkList* p, * q;
int index = 0;
p = L;
if (!L || !L->next) {
return ERROR;
}
while (p->next && index < i - 1) {
p = p->next;
index++;
}
if (!p->next || index > i - 1) {
return ERROR;
}
q = p->next;
p->next = q->next;
free (q);
return OK;
}
void LinkPrint(LinkList* L) {
printf("链表输出:\n");
LinkList* p = NULL;
if (!L) {
printf("链表为空!\n");
return;
}
p = L->next;
while (p) {
printf("%d\t", p->date);
p = p->next;
}
printf("\n");
}
void LinkDextory(LinkList* L) {
LinkList* p = L;
printf("正在销毁单链表...(注:头结点没有值,所以为负数)\n");
while (p) {
L = L->next;
printf("删除元素:%d\n", p->date);
free (p);
p = L;
}
printf("销毁单链表成功!\n");
}
int main() {
LinkList* L = NULL;
LinkList* s = NULL;
L=InitList(L);
if(!L)printf("初始化链表失败\n");
printf("初始化链表成功\n");
int n;
printf("尾插法创建单链表!\n");
printf("请输入您要创建元素的个数:");
scanf_s("%d", &n);
printf("请依次输入%d个元素\n", n);
while (n > 0) {
s = (LinkList*)malloc(sizeof(Node));
scanf_s("%d",&s->date);
ListInsert_back(L, s);
n--;
}
LinkPrint(L);
printf("这里插入3次.\n");
for (int j = 0; j < 3; j++) {
int i, x;
printf("请输入要插入的位置和元素(用空格隔开):\n");
scanf_s("%d %d", &i, &x);
if (LinkInsert(L, i, x)) {
printf("插入成功\n");
}
else {
printf("插入失败\n");
}
LinkPrint(L);
}
if (Link_FindElem(L, 10)) {
printf("查找元素10的位置是:%d\n", Link_FindElem(L, 10));
}
else {
printf("查无此值\n");
}
if (LinkDelete(L, 2)) {
printf("删除第2个元素成功!\n");
LinkPrint(L);
}
else {
printf("删除第2个元素失败\n");
LinkPrint(L);
}
LinkDextory(L);
system("pause");
return 0;
}
|