单向链表
- 链式存储中每个结点都包含两个部分:数据域、指针域。
- 如果节点中只有指向后继的指针,那么这些结点组成的链表成为单向链表。
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int data;
struct node *next;
} node;
node * createList() {
node *ph = (node *)malloc(sizeof(node));
ph->data = 0;
ph->next = NULL;
printf("初始化链表成功...\n");
return ph;
}
void display(node *ph) {
if(!ph) {
printf("传入参数有误!\n");
return;
}
node *p = ph->next;
while(p) {
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int size(node *ph) {
int count = 0;
if(!ph) {
printf("传入参数有误!\n");
return 0;
}
node *p = ph->next;
while(p) {
count++;
p = p->next;
}
return count;
}
void headInsert(node *ph) {
node *s = (node *)malloc(sizeof(node));
s->next = ph->next;
printf("请输入头插结点数据:\n");
scanf("%d", &s->data);
ph->next = s;
}
void endInsert(node *ph) {
node *r = ph;
node *s = (node *)malloc(sizeof(node));
printf("请输入尾插结点数据:\n");
scanf("%d", &s->data);
s->next = NULL;
while(r->next) {
r = r->next;
}
r->next = s;
}
int isNull(node *ph) {
if(ph->next) {
return 0;
} else {
return 1;
}
}
int acquire(node *ph, int pos) {
if(!ph || pos < 1 || pos > size(ph)) {
printf("传入参数有误!\n");
return 0;
}
node *pval = ph->next;
int i;
for(i=1; i<pos; i++) {
pval = pval->next;
}
return pval->data;
}
int find(node *ph, int elem) {
if(!ph) {
printf("传入参数有误!\n");
return 0;
}
node *pcur = ph->next;
int count = 1;
while(pcur) {
if(pcur->data == elem) {
return count;
}
count++;
pcur = pcur->next;
}
}
int insert(node *ph, int pos, int val) {
if(!ph || pos < 0 || pos > size(ph)) {
printf("传入参数有误!\n");
return 0;
}
node *pcur = ph->next;
node *pval = (node *)malloc(sizeof(node));
pval->data = val;
if(pos == 0 || pos == 1) {
pval->next = ph->next;
ph->next = pval;
} else {
int i;
for(i=1; i<pos-1; i++) {
pcur = pcur->next;
}
pval->next = pcur->next;
pcur->next = pval;
}
return 1;
}
void delList(node *ph, int pos) {
if(!ph || pos < 1 || pos > size(ph)) {
printf("传入参数有误!\n");
return;
}
node *pcur = ph;
int i;
for(i=0; i<pos-1; i++) {
pcur = pcur->next;
}
node *s = pcur->next;
pcur->next = s->next;
free(s);
}
node * destroy(node *ph) {
if(!ph) {
printf("传入参数有误!");
return ph;
}
node *pcur;
while(ph) {
pcur = ph;
ph = ph->next;
free(pcur);
}
printf("链表销毁成功...\n");
return ph;
}
void empty(node *ph) {
if(!ph) {
printf("传入参数有误!");
return ;
}
node *pcur = ph->next;
while(pcur) {
ph->next = pcur->next;
free(pcur);
pcur = ph->next;
}
printf("链表清空成功...\n");
}
main() {
node *ph = NULL;
ph = createList();
headInsert(ph);
endInsert(ph);
printf("当前链表是否为空:%s\n", isNull(ph) ? "是":"否");
printf("当前链表长为: %d\n", size(ph));
printf("\n打印当前链表\n");
display(ph);
printf("\n------------1----------------\n");
insert(ph, 2, 99);
insert(ph, 2, 90);
printf("插入99、90结点后的链表\n");
display(ph);
printf("\n删除第一个结点后的链表\n");
delList(ph, 1);
display(ph);
printf("\n当前链表第%d个元素为:%d\n", 2, acquire(ph, 2));
printf("\n当前链表数值为%d的在第%d个结点\n", 22, find(ph, 22));
printf("\n------------2----------------\n");
empty(ph);
printf("清空后链表长为: %d\n\n", size(ph));
ph = destroy(ph);
printf("链表长为: %d\n", size(ph));
}