在这里我会给大家详细介绍数据结构中的各种链表,队列,栈,表,串,排序等算法的详细介绍,
下面我们来介绍带头节点的单链表的具体实现:
要实现一种数据结构,最重要地是能够构思出一种结构,来实现你解决问题的思维(思路)。在带头节点的单链表中,我们可以分析知道,该链表中存在两种结构,①头节点的结构②数据结点的结构:
typedef int Elemtype;
typedef struct ListNode//节点信息
{
Elemtype data;
struct ListNode *next;
}ListNode,*PListNode;
typedef struct List//头节点信息
{
PListNode head;
int cursize;
}List;
这样我们就设计出相应的数据结构,接下来使我们对该单链表的一些与之对应的操作:
☆函数1:结点购买函数
函数2:初始化函数
函数3:判空函数
☆函数4:按位置插入函数
函数5:按位置删除,返回在该位置值的函数
函数6:根据值,返回该节点当前地址函数
函数7:根据值,返回该节点前驱结点地址函数
函数8:根据值,删除节点的函数
★函数9:根据值,删除所有节点值与该值相同的节点
★函数10:链表清除函数
★函数11:链表逆置函数
函数12:链表显示函数
函数13:主函数main
具体实现代码:如下
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
{
Elemtype data;
struct ListNode *next;
}ListNode,*PListNode;
{
PListNode head;
int cursize;
}List;
{
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
if(NULL == p)
{
printf("buynode is error:\n");
exit(1);
}
memset(p,0,sizeof(ListNode));
return p;
}
{
p.head = BuyNode();
p.cursize = 0;
}
{
return p.cursize == 0;
}
{
if(pos<1||pos>p.cursize+1)
{
printf("insert pos is error:\n");
exit(1);
}
PListNode s = p.head;
while(pos-1)
{
--pos;
s = s->next;
}//s指向断开位置的前个结点
PListNode q = BuyNode();
q->data = x;
q->next = s->next;
s->next = q;
}
{
if(pos<1 || pos>p.cursize)
{
printf("delete pos is error:\n");
exit(1);
}
PListNode s = p.head;
while(pos - 1)
{
--pos;
s = s->next;
}
Elemtype x = s->next->data;
PListNode q = s->next;
s->next = q->next;
free(q);
p.cursize -= 1;
return x;
}
PListNode According_Value_Find_Adress(List &p , Elemtype x)
{
PListNode s = p.head->next;
while(s != NULL && s->data != x)
{
s = s->next;
}
return s;
}
PListNode Pre_Find_Value(List &p ,Elemtype x)
{
PListNode s = p.head;
while(s->next != NULL && s->next->data != x)
{
s = s->next;
}
if(s->next == NULL)
{
s =NULL;
}
return s;
}
{
PListNode s = According_Value_Find_Adress(p,x);//要删除的结点
PListNode q = Pre_Find_Value(p,x);//要删除的前驱结点
bool res = false;
if(s != NULL || q !=NULL)
{
q->next = s->next;
free(s);
s = NULL;
res = true;
}
return res;
}
void Remove_All_Val_Node(List &p,Elemtype x)
{
PListNode s = p.head;
while(s->next != NULL)
{
if(s->next->data == x)
{
PListNode r = s->next;
s ->next = r->next;
free(r);
p.cursize -=1;
}
else
{
s =s->next;
}
}
}
{
PListNode s = p.head;
{
PListNode q = s->next;
s->next = q->next;
free(q);
}
p.cursize = 0;
}
{
while(p.cursize < 2)
return;
PListNode q =p.head->next;
while(q!=NULL)
{
PListNode r = q;
q=q->next;
r->next = p.head->next;
p.head->next = r;
}
}
{
PListNode s = p.head->next;
for(int i=0;i<p.cursize;++i)
{
printf("%d ",s->data);
s = s->next;
}
}
{
List p;
InitList(p);
for(int i=1;i<5;++i)
{
Insert_Pos_Node(p,i+10,i);
}
Show_List(p);
printf("%d %d\n",Delete_Pos_Node(p,2),p.cursize);
Show_List(p);
printf("\n");
Show_List(p);
Insert_Pos_Node(p,16,5);
printf("\n");
Show_List(p);
printf("\n");
Show_List(p);
printf("\n");
printf("%d \n",p.cursize);
结果输出:
11 12 13 14
12 4
11 13 14
14 13 11
14 13 11 16 16
14 13 11
0
请按任意键继续. . .