//2013/11/28
//oj上面的题目
//
typedef struct node
{
char data;
node* next;
}Node;
//读取字符串数据到链表
int ReadData(Node* pList,char* strBuf);
//按照规则排序单链表
//前半部分安ascii升序排序;后半部分安ascii降序排序;如果字符串长度为奇数,中间的字符不排序
int SortData(Node* pList);
//读取链表的值到数组
int SaveData(Node* pList,char* strBuf);
//下面是自己需要的函数
//链表的基本操作
//增加一个节点
void AddNode(Node* pList,char data);
//升序排序
void AscendingSrot(Node* pStart,Node* pEnd);
//降序排序
void DescendingSrot(Node* pStart,Node* pEnd);
int LengthList(Node* pNode);
//需找第n个节点
Node* GetIndex(Node* pStart,int nIndex);
#include "buf2list.h"
#include <malloc.h>
#include <stdio.h>
int ReadData( Node* pList,char* strBuf )
{
pList->next = NULL;
char* strTemp = strBuf;
while ( '\0' != *strTemp)
{
AddNode(pList,*strTemp);
strTemp ++;
}
AddNode(pList,*strTemp);
return 1;
}
int SortData( Node* pList )
{
int nLength = LengthList(pList);
Node* pEnd = GetIndex(pList,nLength/2);
AscendingSrot(pList,pEnd);
Node* pStart = GetIndex(pList,(nLength+1)/2);
pEnd = GetIndex(pList,nLength);
DescendingSrot(pStart,pEnd);
return 1;
}
int SaveData( Node* pList,char* strBuf )
{
Node* pTemp = pList->next;
while(pTemp != NULL)
{
*strBuf = pTemp->data;
strBuf++;
pTemp = pTemp->next;
}
return 1;
}
void AddNode( Node* pList,char data )
{
Node* pTemp = pList;
while(pTemp->next != NULL)
{
pTemp = pTemp->next;
}
Node* pNew = (Node*)malloc(sizeof(Node));
pNew->data = data;
pNew->next = NULL;
pTemp->next = pNew;
}
//升序,第一个节点不参与排序
void AscendingSrot( Node* pStart,Node* pEnd )
{
if ( LengthList(pStart)-LengthList(pEnd) < 2)
{
return;
}
//head记录插入位置
Node* head = pStart;
//p记录要查找的节点
Node* p = head->next->next;
//pEndNext记录最后一个节点的下一个节点
Node* pEndNext = pEnd->next;
head->next->next = pEndNext;
while( p!= pEndNext)
{
//q记录p的下一个节点
Node* q = p->next;
while (head->next != pEndNext && head->next->data < p->data)
{
head = head->next;
}
//在head后面插入p
p->next = head->next;
head->next = p;
p = q;
head = pStart;
}
}
int LengthList( Node* pNode )
{
int nLength = 0;
Node* pTemp = pNode;
while(pTemp->next != NULL)
{
nLength++;
pTemp = pTemp->next;
}
return nLength-1;
}
Node* GetIndex( Node* pStart,int nIndex )
{
Node* pTemp = pStart;
for ( int i =0; i< nIndex;i++)
{
pTemp = pTemp->next;
}
return pTemp;
}
void DescendingSrot( Node* pStart,Node* pEnd )
{
if ( LengthList(pStart)-LengthList(pEnd) < 2)
{
return;
}
//head记录插入位置
Node* head = pStart;
//p记录要查找的节点
Node* p = head->next->next;
//pEndNext记录最后一个节点的下一个节点
Node* pEndNext = pEnd->next;
head->next->next = pEndNext;
while( p!= pEndNext)
{
//q记录p的下一个节点
Node* q = p->next;
while (head->next != pEndNext && head->next->data > p->data)
{
head = head->next;
}
//在head后面插入p
p->next = head->next;
head->next = p;
p = q;
head = pStart;
}
}
#include "buf2list.h"
int main()
{
char* strTest="bcazfde";
Node start;
ReadData(&start,strTest);
SortData(&start);
char strOut[100] = {0};
SaveData(&start,strOut);
return 0;
}