目录
基于带头结点链表实现的几种算法
typedef int ElemType;
struct node //数据结点的类型
{
ElemType data;//数据域
struct node *next;//指针域
};
struct List //头结点的类型
{
struct node *first;//指向第一个数据结点
struct node *last;//指向最后一个数据结点
int nodeNum;//数据结点的数量
/*
.... 其他属性
*/
};
1.选择排序
struct List *sort_a_list_xuanzhe(struct List *list)
{
struct node *pa = list->first;
while(pa)
{
struct node *pb = pa->next;
struct node *psave = pa;
int min = pa->data;
while(pb)
{
if(pb->data <= min)
{
min = pb->data;
psave = pb;
}
pb = pb->next;
}
int temp = psave->data;
psave->data= pa->data;
pa->data = temp;
pa = pa->next;
}
return list;
}
2.冒泡排序
struct List *sort_a_list_maopao(struct List *list)
{
int temp = 0;
struct node *p = NULL;
for(int i =0;i<list->nodeNum-1;i++)
{
p = list->first;
for(int j=0;j<list->nodeNum-1-i;j++)
{
if(p->data > p->next->data)
{
temp = p->data;
p->data = p->next->data;
p->next->data = temp;
}
p = p->next;
}
}
return list;
}
3.创建有序链表
struct List *sort_a_list(struct List *list)
{
/*step1: 创建一个新的头结点*/
struct List *list1 = malloc(sizeof(*list1));
list1->first = NULL;
list1->last = NULL;
list1->nodeNum = list->nodeNum;
/*step2: 把原来的链表的数据结点拆下来*/
struct node *p = list->first;//p指向拆下来的结点
while(p)
{
list->first = list->first->next;
p->next = NULL;
/*step3: 把拆下来结点用头插法插入到新的链表*/
if(list1->first==NULL || list1->last==NULL)
{
list1->first = p;
list1->last = p;
}
else //从少到多
{
struct node *p1 = list1->first;
struct node *pre;
while(p1)
{
if(p1->data > p->data)//找到第一个比插入的结点大的结点
break;
pre = p1;
p1 = p1->next;
}
if(p1 != NULL)//找到了
{
if(p1 == list1->first)
{
p->next = list1->first;
list1->first = p;
}
else
{
pre->next = p;
p->next = p1;
}
}
else //没找到
{
list1->last->next = p;
list1->last = p;
}
}
p = list->first;//p往后走
}
free(list);
return list1;
}
4.求两链表的交集
struct List *common_of_lists(struct List *listA,struct List *listB)
{
struct List *ListC = malloc(sizeof(*ListC));
ListC->first = NULL;
ListC->last = NULL;
ListC->nodeNum = 0;
struct node *p_a = listA->first;
struct node *p_b = listB->first;
struct node *p_c = NULL;
while(p_a&&p_b)
{
if(p_a->data > p_b->data)
{
p_b = p_b->next;
}
else if(p_a->data < p_b->data)
{
p_a = p_a->next;
}
else
{
p_c = malloc(sizeof(*p_c));
p_c->data = p_a->data;
p_c->next = NULL;
if(ListC->first==NULL || ListC->last==NULL)
{
ListC->first = p_c;
ListC->last = p_c;
}
else
{
ListC->last->next = p_c;//尾插
ListC->last = p_c;
}
p_a = p_a->next;
p_b = p_b->next;
ListC->nodeNum++;
}
}
return ListC;
}
5.利用快慢指针寻找中间值
struct node *find_middle_node(struct List *list)
{
struct node *p1 = list->first;
struct node *p2 = list->first;
while(p2)
{
p2 = p2->next->next;
p1 = p1->next;
}
return p1;
}
基于双向链表,判断子链表
void judge_sublist(struct List *ListA,struct List *ListB)
{
struct node *p_a = ListA->first;
struct node *p_b = ListB->first;
struct node *p_start = ListA->first;
while(p_a && p_b)
{
if(p_a->data == p_b->data)
{
p_a = p_a->next;
p_b = p_b->next;
}
else
{
p_start = p_start->next;
p_b = ListB->first;
p_a = p_start;
}
}
if(!p_b)
{
printf("yes\n");
}
else
printf("no\n");
}