带头节点的单链表
作者:互联网
单链表特点:逻辑上相邻,物理上不一定相邻
头插o(1) 随机插入以及尾插 o(n)
头删o(1) 按位置按值删除或尾删 o(n)
查找 o(n)
结构体设计:
typedef struct Node {
int data;
Node* next;
}Node,*PNode;
初始化函数:
PNode Init_list(PNode head) {
Node* s = (Node*)malloc(sizeof(Node));
assert(s!=NULL);
s->next = NULL;
return s;
}
头插:
bool Insert_Head(PNode plist, int val) {
assert(plist != NULL);
PNode s = (PNode)malloc(sizeof(Node)); //1
assert(s != NULL);
s->data = val;
//2
s->next = plist->next; //3
plist->next = s;
return true;
}
尾插:
bool Insert_Tail(PNode plist, int val) {
assert(plist != NULL);
PNode s = (Node*)malloc(sizeof(Node));
assert(s!=NULL);
//PNode pr = plist;
//PNode p = plist->next;
//while (p != NULL) {
// p = p->next;
// pr = pr->next;
//}
//pr->next = s;
PNode p = plist;
for (; p->next != NULL; p = p->next) {
}
p->next = s;
s->next = NULL;
return true;
}
按位置插
bool Insert_Pos(PNode plist, int pos, int val) {
assert(plist != NULL && pos >= 0 && pos <= Get_Length(plist));
PNode s = (Node*)malloc(sizeof(Node));
assert(s!=NULL);
s->data=val;
PNode p = plist;
for (int i = 0; i < pos; i++) {
p = p->next;
}
s->next = p->next;
p->next = s;
return true;
}
查找: 在plist指向的单链表中值为val的第一个节点 找到后返回其地址,否则返回NULL
PNode Search(PNode plist, int val) {
assert(plist != NULL);
PNode p = plist->next;
while (p->data != val) {
p = p->next;
}
return p;
}
头删
bool Del_Head(PNode plist) {
PNode p = plist->next;
plist->next = p->next;
free(p);
p = NULL;
return true;
}
尾删
bool Del_Tail(PNode plist) {
PNode p = plist;
for (; p->next != NULL; p = p->next) {
if (p->next->next == NULL) {
break;
}
}
PNode q = p->next;
p->next = q->next;
free(q);
q = NULL;
return true;
}
按位置删
bool Del_Pos(PNode plist, int pos) {
//assert()
PNode pr = plist;
PNode p = plist->next;
for (int i = 0; i < pos; i++) {
pr = pr->next;
p = p->next;
}
pr->next = p->next;
free(p);
p = NULL;
return true;
}
按值删
bool Del_Val(PNode plist, int val) {
assert(plist != NULL);
PNode p = GetPrior(plist, val);
if (p == NULL) {
return false;
}
PNode q = p->next;
p->next = q->next;
free(q);
q = NULL;
return true;
//PNode pr = plist;
//PNode p = plist->next;
//while (p->data != val) {
// pr = pr->next;
// p = p->next;
//}
//pr->next = p->next;
//free(p);
//p = NULL;
//return true;
}
判空
bool IsEmpty(PNode plist) {
return plist->next == NULL;
}
获取前驱(将值为val的节点的前一个节点返回)
PNode GetPrior(PNode plist, int val) {
PNode p = plist;
for (; p->next != NULL; p = p->next) {
if (val == p->next->data) {
return p;
}
}
return NULL;
}
获取后继
PNode Get_Next(PNode plist, int val) {
PNode p = Search(plist, val);
return p->next;
}
获取有效节点个数
int Get_Length(PNode plist) {
assert(plist != NULL);
int i = 0;
for (PNode p = plist->next; p != NULL; p = p->next) {
//printf("%d ", p->data);
i++;
}
return i;
}
打印函数
void Print(PNode plist) {
assert(plist != NULL);
PNode p = plist->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
标签:单链,带头,val,NULL,节点,PNode,return,next,plist 来源: https://blog.csdn.net/weixin_50626842/article/details/120771929