Hello!第一次写博客,来总结自己所学到的知识,希望在这条路上越走越远。
#include <stdio.h>
#include <stdbool.h>
typedef struct LNode
{
int data;
struct LNode *next;
} LNode, *LinkList;
/* 初始化链表 */
bool InitLinkList(LinkList *l)
{
(*l) = NULL;
return true;
}
bool EmptyLinkList(LinkList l)
{
return (l == NULL);
}
bool InsertLinkList(LinkList *l, int offset, int data)
{
if (offset < 1) {
return false;
}
/* 当插入位置为 1 的时候单独处理 */
if (offset == 1) {
LNode *p = (LNode*)malloc(sizeof(LNode));
p->data = data;
p->next = *l;
*l = p;
}
LNode *s;
/* 指向当前位置 */
int j = 1;
s = *l;
while (s != NULL && j < offset - 1) {
s = s->next;
j++;
}
/* 说明插入位置不正确 */
if (s == NULL) {
return false;
}
LNode *p = (LNode *)malloc(sizeof(LNode));
/* 链表的断链和挂链 */
p->data = data;
p->next = s->next;
s->next = p;
return true;
}
bool DeleteLNode(LinkList *l, int offset)
{
if (offset < 1) {
return false;
}
if (offset == 1) {
*l = (*l)->next;
return true;
}
LNode *p;
int j = 1;
p = *l;
while (p != NULL && j < offset - 1) {
p = p->next;
j++;
}
if (p == NULL || p->next == NULL) {
return false;
}
LNode *q;
q = p->next;
p->next = q->next;
free(q);
return true;
}
int main()
{
LinkList l;
InitLinkList(&l);
printf("%d\n", EmptyLinkList(l));
printf("%d\n", InsertLinkList(&l, 1, 7));
printf("%d\n", InsertLinkList(&l, 2, 1));
printf("%d\n", InsertLinkList(&l, 3, 3));
printf("%d\n", DeleteLNode(&l, 1));
while(l != NULL) {
printf("%d\n", l->data);
l = l->next;
}
return 0;
}