c语言实现单向链表
#include <stdio.h>
#include<stdlib.h>
typedef int Status;
typedef int ElemType;
typedef struct LNode {
ElemType data;
struct LNode* next;
}LNode;
LNode* initLink() {
LNode* p = (LNode*)malloc(sizeof(LNode));
LNode* temp = p;
for (int i = 1; i < 5; i++) {
LNode* a = (LNode*)malloc(sizeof(LNode));
a->data = i;
a->next = NULL;
temp->next = a;
temp = temp->next;
}
return p;
}
void createlist(LNode* L, int n) {
for (int i = n; i > 0; --i) {
LNode* p = (LNode*)malloc(sizeof(LNode));
printf("输入结点的值:");
scanf("%d",&p->data);
p->next = NULL;
L->next = p;
L = L->next;
}
}
Status Insert(LNode* L, int i, int e) {
int j ;
LNode* p;
p = L;
for (j = 1; j < i; j++) {
if (p->next) {
p = p->next;
}
else {
printf("插入位置不当");
return 0;
}
}
LNode* q = (LNode*)malloc(sizeof(LNode));
q->data = e;
q->next = p->next;
p->next = q;
return 1;
}
Status Delete(LNode* L, int i) {
LNode* p = L;
int j;
for (j = 1; j < i; j++) {
if (p->next) {
p = p->next;
}
else {
printf("删除位置不当");
return 0;
}
}
LNode* q = p->next;
p->next = q->next;
free(q);
return 1;
}
Status find(LNode* L, int n) {
LNode* p = L;
for (int i = 0; i < n;i++) {
if (p->next) {
p = p->next;
}
else {
printf("查询位置不当");
return 0;
}
}
printf("第%d个元素是%d\n",n, p->data);
}
Status change(LNode* L, int n,int e) {
LNode* p = L;
for (int i = 0; i < n; i++) {
if (p->next) {
p = p->next;
}
else {
printf("修改位置不当");
return 0;
}
}
p->data = e;
return 1;
}
Status getlength(LNode* L) {
LNode* p = L;
int length=0;
while (p->next) {
length++;
p = p->next;
}
printf("链表长度为%d\n ", length);
}
void display(LNode* L) {
LNode* temp = L;
while (temp->next) {
temp = temp->next;
printf("%d\n ", temp->data);
}
}
int main() {
int m;
LNode *L= (LNode*)malloc(sizeof(LNode));
L->next = NULL;
createlist(L,5);
m = getlength(L);
display(L);
return 0;
}