几个简单C语言算法

1. 链表逆置

// List.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

struct Node
{
	int value;
	Node *next;

	Node()
	{
		value = -1;
		next = 0;
	}

	~Node()
	{
		value = -1;
		next = 0;
	}
};



Node * create_list( int n );
void print_list( const Node *header );
Node* reservse_list( Node *header);
void destory_list( Node *header );

int quick_a_pass( int *pArray, int i, int j);

void quick_sort( int *pArray, int i, int j );

int main(int argc, char* argv[])
{
    Node *header = create_list( 1 );
	print_list( header );

	printf("---------------------------------------------------------------\n");

	Node *pTail = reservse_list( header );
	print_list( pTail );

	printf("---------------------------------------------------------------\n");

	destory_list( pTail );

	printf("---------------------------------------------------------------\n");

	int array[10] = {2, 4, 1, 8, 9, 0, 7, 3, 5, 6};
	quick_sort( array, 0, 9 );
	for ( int i = 0; i < 10; ++i )
	{
		printf("%d  ", array[i]);
	}


	printf("Hello World!\n");
	return 0;
}



Node * create_list( int n )
{
	int i = 0;
	Node *pHeader = NULL;
	Node *pCurrent = NULL;
	while ( i < n )
	{
		Node *pNode = new Node;
		pNode->value = i + 1;
        if ( NULL == pHeader )
		{
			pCurrent = pHeader = pNode;
		}
		else
		{
			pCurrent->next = pNode;
			pCurrent = pNode;
		}

		++i;
	}

	return pHeader;
}



void print_list( const Node *header )
{
	int nCount = 0;
	while ( header != NULL )
	{
		printf("Current Node Index %d-- > Value %d\n", nCount++, header->value );
		header = header->next;
	}
}


Node* reservse_list( Node *header)
{
	Node *pFirst = header;
	Node *pCurrent = NULL;

	while( pFirst != NULL )
	{

		if ( NULL == pCurrent )
		{
			pCurrent = pFirst;			
			pFirst = pFirst->next;
			pCurrent->next = NULL;
		}
		else
		{
			Node *pTemp = pFirst->next;
		    pFirst->next = pCurrent;
			pCurrent = pFirst;	
			pFirst = pTemp;
		}
	}

	return pCurrent;
}


void destory_list( Node *header )
{
	int nCount = 0;
	while ( header != NULL )
	{
		printf("Destory Node %d\n", nCount++ );
		Node *Temp = header->next;
		delete header;
		header = Temp;
	}
}


int quick_a_pass( int *pArray, int i, int j)
{
	int k = i;
	int nTemp = pArray[i];

     while ( i < j )
	 {
		 while ( i < j )
		 {
			 if ( pArray[i] < nTemp ) ++i;
			 else break;
		 }

		 while ( i < j )
		 {
			 if ( pArray[j] > nTemp ) j--;
			 else break;
		 }

		 if ( i < j )
		 {
			 int nSwap = pArray[j];
			 pArray[j] = pArray[i];
			 pArray[i] = nSwap;
		 }
	 }

	return i;
}



void quick_sort( int *pArray, int i, int j )
{
	if ( i > j )
	{
		return;
	}

	if ( i < 0 )
	{
		return;
	}

	if ( j < 0 )
	{
		return;
	}

	if ( i == j )
	{
		return;
	}

	int nIndex = quick_a_pass( pArray, i, j );
	quick_sort(pArray, i, nIndex -1 );
	quick_sort(pArray, nIndex + 1, j );
}


2. 快速排序

你可能感兴趣的:(几个简单C语言算法)