c语言实现数据结构中的链表源代码

时间:2021-12-22 01:43:49
#include <stdio.h>
#include <stdlib.h>

typedef struct LNode *List;
struct LNode {
int data;
List next;
};
struct LNode L;

List InitList(List PtrL) {
PtrL = (List) malloc(sizeof(L));
PtrL->next = NULL;
return PtrL;
}

List CreateFromHead(List PtrL, int x) { //头插法创建链表,最先创建的元素为链表尾
List s;
s = (List) malloc (sizeof(L));
s->data = x;
s->next = PtrL->next;
PtrL->next = s;
return PtrL;
}

List CreateFromTail(List PtrL) { //尾插法创建链表
List s, r;
int a[20], n;
r = PtrL;
printf("请输入要创建链表元素的个数:");
scanf("%d", &n);
printf("请输入要创建链表元素的值:");
for(int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
s = (List) malloc (sizeof(L));
s->data = a[i];
s->next = r->next;
r->next = s;
r = s;
}
return PtrL;
}

int Length(List PtrL) {
List p;
int i = 0;
p = PtrL->next;
while(p) {
i++;
p = p->next;
}
return i;
}

List FindKth(List PtrL, int k) { //查找链表中第k个节点
List p = PtrL;
int i = 0;
while(p != NULL && i < k) {
p = p->next;
i++;
}
if(i == k) return p;
else return NULL;
}

List Insert(List PtrL, int i, int x) {
List p, s;
if(i == 1) {
s = (List) malloc(sizeof(L));
s->data = x;
s->next = PtrL;
return s;
}
p = FindKth(PtrL,i-1);
if(p == NULL) {
printf("参数i错");
return NULL;
}
else {
s = (List) malloc(sizeof(L));
s->data = x;
s->next = p->next;
p->next = s;
return PtrL;
}

}

List Delete(List PtrL, int i) {
List p, s;
if(i == 1) {
s = PtrL;
if(PtrL != NULL) PtrL = PtrL->next;
else return NULL;
free(s);
return PtrL;
}
p = FindKth(PtrL,i-1);
if(p == NULL) {
printf("第%d个结点不存在",i-1);
return NULL;
}
else if(p->next == NULL) {
printf("第%d个结点不存在",i);
return NULL;
}
else {
s = p->next;
p->next = s->next;
free(s);
return PtrL;
}
}


void print(List PtrL) {
List start;
for(start = PtrL->next; start != NULL; start=start->next)
printf("%d ",start->data);

}


int main() {
List list, s;
int n, m;
list = InitList(list);
list = CreateFromTail(list); //取决你用头插法创建链表还是尾插法创建链表,为了让输出看着简单点,插入和删除我就直接写死了
printf("使用尾插法创建链表为:");
print(list);
printf("\n");
list = Insert(list,3,9);
printf("插入元素后的链表为:");
print(list);
printf("\n");
m = Length(list);
printf("链表的长度的为:%d", m);
printf("\n");
Delete(list,2);
printf("删除结点后的链表为:");
print(list);
printf("\n");
m = Length(list);
printf("删除结点后的链表长度为:%d", m);
printf("\n");
s = FindKth(list,3);
printf("您查找的节点值为:%d", s->data);
return 0;
}

c语言实现数据结构中的链表源代码