C语言实现单链表
带头结点的单链表
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int ElemType;
typedef struct LNode {
ElemType data;
struct LNode *next;
}LNode, *LinkList;
bool initList(LinkList *L) {
(*L) = (LNode *)malloc(sizeof(LNode));
if ((*L) == NULL) {
return false;
}
(*L)->next = NULL;
return true;
}
bool listHeadInsert(LinkList *L) {
(*L) = (LNode *)malloc(sizeof(LNode));
(*L)->next = NULL;
if ((*L) == NULL)
return false;
LNode *s;
ElemType value;
scanf("%d", &value);
while (value != 9999) {
s = (LNode *)malloc(sizeof(LNode));
s->data = value;
s->next = (*L)->next;
(*L)->next = s;
scanf("%d", &value);
}
return true;
}
bool listTailInsert(LinkList *L) {
(*L) = (LNode *)malloc(sizeof(LNode));
(*L)->next = NULL;
if ((*L) == NULL)
return false;
LNode *s, *r = (*L);
ElemType value;
scanf("%d", &value);
while (value != 9999) {
s = (LNode *)malloc(sizeof(LNode));
s->data = value;
r->next = s;
r = s;
scanf("%d", &value);
}
r->next = NULL;
return true;
}
bool listInsert(LinkList L, int i, ElemType e) {
if (i < 1)
return false;
LNode *p;
int j = 0;
p = L;
while (p != NULL && j < i - 1) {
p = p->next;
j++;
}
if (p == NULL)
return false;
LNode *s = (LNode *)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
bool insertNextNode(LNode *p, ElemType e) {
if (p == NULL)
return false;
LNode *s = (LNode *)malloc(sizeof(LNode));
if (s == NULL)
return false;
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
bool insertPriorNode01(LNode *p, ElemType e) {
if (p == NULL)
return false;
LNode *s = (LNode *)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
ElemType temp = p->data;
p->data = s->data;
s->data = temp;
return true;
}
bool insertPriorNode02(LinkList L, LNode *p, ElemType e) {
if (L == NULL || p == NULL)
return false;
LNode *h;
h = L;
while (h != NULL && h->next != p) {
h = h->next;
}
if (h == NULL)
return false;
insertNextNode(h, e);
return true;
}
LNode * getElemByLocation(LinkList L, int pos) {
int j = 0;
if (pos < 1)
return NULL;
while (L && j < pos) {
L = L->next;
j++;
}
if (L == NULL)
return NULL;
return L;
}
bool listDelete(LinkList L, int i, ElemType *e) {
if (i < 1)
return false;
LNode *p;
int j = 0;
p = L;
while (p != NULL && j < i - 1) {
p = p->next;
j++;
}
if (p == NULL)
return false;
if (p->next == NULL)
return false;
LNode *q = p->next;
*e = q->data;
p->next = q->next;
free(q);
return true;
}
bool deleteNode(LNode *p) {
if (p == NULL)
return false;
LNode *q = p->next;
p->data = p->next->data;
p->next = q->next;
free(q);
return true;
}
bool isEmpty(LinkList L) {
if (L->next == NULL) {
return true;
} else {
return false;
}
}
void printList(LinkList L) {
if (L->next == NULL)
return;
LNode *p = L->next;
while (p != NULL) {
printf("%d\t", p->data);
p = p->next;
}
printf("\n");
}
int main() {
LinkList L;
listTailInsert(&L);
printList(L);
LNode *result = getElemByLocation(L, 3);
insertPriorNode02(L,result, 666);
printList(L);
}