本程序主要实现c语言双向链表冒泡排序的功能,代码如下,需要者可以自取。(你电同学可以借鉴排序功能,但最好还是看懂后自己写)
难点分析:第一个交换需要引出前驱和最后一个的交换需要引出后继节点。
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Lnode
{
int data;
struct Lnode *next,*prior;
}Lnode;
typedef struct List{
Lnode *head;
Lnode *tail;
int length;
}list;
void Creatlist(list *table) //创建双向链表
{
int x,i;
Lnode *temp,*t,*p;
table->head=NULL;
table->tail=NULL;
table->length=0;
x=1;
scanf("%d",&x);
for(i=0;x!=0;i++)
{
/*fflush(stdin);*/
temp=(Lnode*)malloc(sizeof(Lnode));
temp->data=x;
temp->next=NULL;
temp->next=table->head;
table->head=temp;
table->length++;
scanf("%d",&x);
}
t=table->head;
t->prior=NULL;
for(i=2;i<=table->length;i++)
{
p=t;
t=t->next;
t->prior=p;
}
}
void Show_list(list *table) //遍历打印双向链表
{
int x,i;
Lnode *temp;
printf("\nThe list is %d num:\n",table->length);
temp=table->head;
while(temp->next!=NULL)
{
temp=temp->next;
}
for(i=0;i<table->length;i++)
{
x=temp->data;
printf("%d\n",x);
temp=temp->prior;
}
}
void sort(list *table)
{
//判空
if (table == NULL)
{
return;
}
//初始化辅助指针
Lnode *pPre = table->head;
Lnode *pCurrent = table->head;
// //循环次数
int num = table->length;
int i,j;
for (i = 1; i < num; i++)
{
//重置指针位置
pPre = table->head;
pCurrent = pPre->next;
for (j = 1; j <= num-i; j++)/*循环条件*/
{
if(pPre->data > pCurrent->data)
{
if (pCurrent->next == NULL) //节点尾节点情况
{
pPre->next = pCurrent->next;
pCurrent->prior = pPre->prior;
pCurrent->next = pPre;
pPre->prior->next = pCurrent;
pPre->prior = pCurrent;
break;
}
if (pPre->prior == NULL) //节点头节点情况
{
table->head = pCurrent;
//pPre与新前驱建立联系
/*pPre->prior->next = pCurrent;*/
pCurrent->prior = pPre->prior;
//pCurrent与新后驱建立联系
pCurrent->next->prior = pPre;
pPre->next = pCurrent->next;
//pPre与pCurrent互连
pPre->prior = pCurrent;
pCurrent->next = pPre;
//pCurrent指针后移到pPre前面
pCurrent = pPre->next;
continue;
}
//非尾节点情况
//交换节点
//指针转换 此处注意6个指针交换
//pPre与新前驱建立联系
pPre->prior->next = pCurrent;
pCurrent->prior = pPre->prior;
//pCurrent与新后驱建立联系
pCurrent->next->prior = pPre;
pPre->next = pCurrent->next;
//pPre与pCurrent互连
pPre->prior = pCurrent;
pCurrent->next = pPre;
//pCurrent指针后移到pPre前面
pCurrent = pPre->next;
}
//pPre->data > pCurrent->data非真情况下
else
{
pPre = pPre->next;
pCurrent = pCurrent->next;
}
}
}
}
int main()
{
list table;
printf("Please input the number to creat the list\n");
Creatlist(&table);
Show_list(&table);
sort(&table);
printf("\nAfter sort become:\n");
Show_list(&table);
}
代码演示略,输入以0结束