现在的位置: 首页 > 综合 > 正文

交换单向链表的相邻节点

2013年06月05日 ⁄ 综合 ⁄ 共 1675字 ⁄ 字号 评论关闭
#include <stdlib.h>
#include <stdio.h>

//The struct of list node 
typedef struct Node 
{
	int		iData;
	struct Node* pNext;
}LNode;

/**
 * Swap the place between two near nodes
 */
void nearLNodeSwap(LNode** pList)
{
	//Nothing to do in the case of pList is NULL or just has one node
	if(NULL == pList || NULL == *pList || NULL == (*pList)->pNext) 
		return ;
	
	LNode* pre = NULL;
	LNode* p = *pList;
	LNode* q = p->pNext;
	
	while(p != NULL && q != NULL)
	{
		if(p == (*pList)) //Head node
		{
			*pList = q;
		}
		else				  //Other nodes
		{
			pre->pNext = q;
		}
		
		p->pNext = q->pNext;
		q->pNext = p;
		pre = p;

		p = p->pNext;
		if(p != NULL)
			q = p->pNext;
	}
}

/**
 *Create a List and init all of the nodes 
 *pList: the List be created
 *listSize: list size
 *return:return list size if success. otherwise return -1
 */
int initList(LNode ** pList,const int listSize)
{
	LNode *newNode = NULL;

	//Init falure and return 0
	if(listSize <= 0)
		return -1;
	
	//Init the head element
	*pList = newNode = (LNode*)malloc( sizeof(LNode) );

	if(NULL == newNode)
	{
		printf("Error:malloc!\n");
		return -1;
	}
	newNode->iData = 1;
	newNode->pNext = NULL;

	//Init the other elements
	for(int i = 1; i < listSize; ++i)
	{
		newNode->pNext = (LNode*)malloc( sizeof(LNode) );
		if(NULL == newNode)
		{
			printf("Error:malloc!\n");
			return -1;
		}

		newNode = newNode->pNext;
		newNode->iData = i+1;
		newNode->pNext = NULL;
	}
	
	//Init success and return list size
	return listSize;
}

/**
 *Print the list data
 *pList: the point of list head
 */
void printList(LNode* pList)
{
	LNode* pNode = pList;

	while(NULL != pNode)
	{
		printf("%d ",pNode->iData);
		pNode = pNode->pNext;
	}
	printf("\n");
}

/**
 * Destroy the List and  release the resources
 */
void destroyList(LNode** pList)
{
	LNode* pNode;

	while(NULL != *pList)
	{
		 pNode = *pList;
		*pList = (*pList)->pNext;
		free(pNode);
	}
}

int main()
{
	LNode* pList = NULL;

	initList(&pList,11);

	printf("Before swap:\n");
	printList(pList);

	//Begin swap the list
	nearLNodeSwap(&pList);

	printf("After swap:\n");
	printList(pList);

	destroyList(&pList);
	getchar();
	return 0;
}

 

抱歉!评论已关闭.