/*
* LinkList.c
*
* Created on: 2016年9月4日
* Author: Edwards
*/
#include <stdlib.h>
#include"LinkList.h"
const int null = 0;
void setnull(struct LNode **p) {
*p = null;
}
int length(struct LNode **p) {
int n = 0;
struct LNode *q = *p;
while (q != null) {
n++;
q = q->next;
}
return (n);
}
ElemType get(struct LNode **p, int i) {
int j = 1;
struct LNode *q = *p;
while (j < i && q != null) {
q = q->next;
j++;
}
if (q != null) {
return (q->data);
} else {
printf("位置参数不正确!\n");
return NULL;
}
}
int locate(struct LNode **p, ElemType x) {
int n = 0;
struct LNode *q = *p;
while (q != null && q->data != x) {
q = q->next;
n++;
}
if (q == null)
return (-1);
else
return (n + 1);
}
void insert(struct LNode **p, ElemType x, int i) {
int j = 1;
struct LNode *s, *q;
s = (struct LNode *) malloc(sizeof(struct LNode));
s->data = x;
q = *p;
if (i == 1) {
s->next = q;
*p = s;
} else {
while (j < i - 1 && q->next != null) {
q = q->next;
j++;
}
if (j == i - 1) {
s->next = q->next;
q->next = s;
} else
printf("位置参数不正确!\n");
}
}
void delete(struct LNode **p, int i) {
int j = 1;
struct LNode *q = *p, *t;
if (i == 1) {
t = q;
*p = q->next;
} else {
while (j < i - 1 && q->next != null) {
q = q->next;
j++;
}
if (q->next != null && j == i - 1) {
t = q->next;
q->next = t->next;
} else
printf("位置参数不正确!\n");
}
if (t != null)
free(t);
}
void display(struct LNode **p) {
struct LNode *q;
q = *p;
printf("单链表显示: ");
if (q == null)
printf("链表为空!");
else if (q->next == null)
printf("%d\n", q->data);
else {
while (q->next != null) {
printf("%d->", q->data);
q = q->next;
}
printf("%d", q->data);
}
printf("\n");
}
c实现单链表
最新推荐文章于 2022-10-22 19:23:57 发布