[作业]单链表的创建、插入、删除、查找
#include "stdio.h"
#include "malloc.h"
typedef struct LNode {
int data;
struct LNode *next;
}LNode, *LinkList;
LNode* InitLList(int low, int up) {
LNode *head, *s, *r;
head = (LNode *)malloc(sizeof(LNode));
r = (LNode *)malloc(sizeof(LNode));
head->data = 9527;
head->next = r;
r->data = low;
r->next = NULL;
for (int i = low + 1; i <= up; i++) {
s = (LNode *)malloc(sizeof(LNode));
s->data = i;
s->next = r->next;
r->next = s;
r = s;
}
return head;
}
void InsertLList(LNode* l, int pos, int num) {
int count;
LNode *s, *p;
if (!l) {
printf("链表不存在");
return;
}
if (pos<1) {
printf("插入位置不存在");
}
p = l->next;
count = 1;
while (count<pos - 1 && p) {
p = p->next;
count++;
}
s = (LNode*)malloc(sizeof(LNode));
s->data = num;
s->next = p->next;
p->next = s;
}
void DelLLink_p(LNode* l, int pos) {
int count;
LNode *p, *q;
if (!l) {
printf("链表不存在");
}
if (pos<1) {
printf("删除位置不存在");
}
p = l->next;
count = 1;
while (count<pos - 1 && p) {
p = p->next;
count++;
}
if (p->next != NULL) {
q = p->next;
p->next = q->next;
free(q);
}
}
int GetLList_p(LNode* l, int pos) {
int count, i;
LNode *p, *q;
if (!l) {
printf("链表不存在");
return 0;
}
if (pos<1) {
printf("删除位置不存在");
}
p = l->next;
count = 1;
while (count<pos && p) {
p = p->next;
count++;
}
return p->data;
}
void PrintLList(LNode* l) {
LNode* s;
s = l->next;
while (s) {
printf("%d\t", s->data);
s = s->next;
}printf("\n");
}
int main() {
LNode* L1;
printf("创建链表: \n");
L1 = InitLList(5, 15);
PrintLList(L1);
printf("链表插入操作: \n");
InsertLList(L1, 5, 555);
PrintLList(L1);
printf("链表删除操作: \n");
DelLLink_p(L1, 6);
PrintLList(L1);
printf("链表查找操作: \n");
int num_5 = GetLList_p(L1, 5);
printf("%d\n",num_5);
}