查找单链表的倒数第k个节点,要求只能遍历一次链表


源文件:

#include "LinkList.h"
#include 
#include 

// 在单链表的尾部插入一个节点
void PushBack(PNode* pHead, DataType data)
{
	PNode pCurNode = NULL;
	PNode pNewNode = NULL;
	assert(pHead);
    pNewNode = BuyNode(data);
	if(pNewNode == NULL)
		return;
	if(*pHead == NULL)
	{
		*pHead = pNewNode;
	}
	else
	{
		pCurNode = *pHead;
		while(pCurNode->_pNext)
		{
			pCurNode = pCurNode->_pNext;
		}
		pCurNode->_pNext = pNewNode;
	}
}
// 构建一个新节点
Node* BuyNode(DataType data)
{
	PNode pNewNode = (Node*)malloc(sizeof(Node));
	if(pNewNode == NULL)
		return NULL;
	pNewNode->_data = data;
	pNewNode->_pNext = NULL;
	return pNewNode;
}

// 正向打印单链表
void PrintList(PNode pHead)
{
	if(pHead == NULL)
		return;
	while(pHead)
	{
		printf("%d->",pHead->_data);
		pHead = pHead->_pNext;
	}
	printf("NULL\n");
}

// 查找单链表的倒数第K个结点,要求只遍历一次链表
PNode FindLastKNode(PNode pHead, size_t k)
{
	PNode pFastNode = NULL;
	PNode pSlowNode = NULL;
	if(pHead == NULL)
		return NULL;
	pSlowNode = pHead;
	pFastNode = pHead;
	while(--k)
	{
		pFastNode = pFastNode->_pNext;
		if(pFastNode == NULL)
			return NULL;
	}
	while(pFastNode->_pNext)
	{
		pSlowNode = pSlowNode->_pNext;
		pFastNode = pFastNode->_pNext;
	}
	return pSlowNode;
}

//销毁单链表,释放空间 
void DestroyList(Node* pHead)   
{  
    while(pHead)  
    {  
        Node* temp = pHead;  
		pHead = pHead->_pNext;  
        free(temp);  
    }  
}  


测试文件:


#include "LinkList.h"
void test()
{
	PNode node = NULL;
	PushBack(&node,1);
	PushBack(&node,3);
	PushBack(&node,5);
	PushBack(&node,4);
	PushBack(&node,2);
	PushBack(&node,6);
	PrintList(node);
	node = FindLastKNode(node,3);
	printf("从倒数第k个结点开始的链表:\n");
	PrintList(node);
	DestroyList(node);
}
int main()
{
	test();
	return 0;
}




你可能感兴趣的:(刷题库,数据结构)