题目:
//删除单链表中倒数第k个节点。
思路:
//首先先找到这个节点,分别利用两个指针,pFast和pSlow,让pFast先走k步,(如果k大于链表的长度直接返回空)再两者同时移动,直到pfast为空,或pfst->next为空。
//此时pslow所指向的节点就是要删除的节点。
//删除这个节点分两种情况进行,第一种是这个节点是头节点,此时要将链表的头指针指向这个节点的下个节点,要在函数里修改主函数中pHead的指向,
//所以参数的类型需要指针的引用或二级指针。第二种情况就是普通的删除了。
#include<iostream>
using namespace std ;
#include <cassert>
struct Node
{
int value;
struct Node * Next;
Node(int data):value(data),Next(NULL) { }
};
void DelLastKNode(Node*& pHead, size_t k) //删除倒数第k个节点。 指针的引用。
{
assert (pHead);
Node *pFast = pHead;
Node *pSlow = pHead;
while (k--) //这里条件还可以写成--k
{
// 如果k太大了,超出了链表的长度,直接返回Null.
if (pFast == NULL) //如果是--k,这里对应的为pFast->Next == NULL
{
return ;
}
pFast = pFast->Next;
}
while (pFast != NULL) //如果是--k,对应的为pFast->Next != NULL
{
pFast = pFast->Next;
pSlow = pSlow->Next;
}
//删除找到的节点。
if (pSlow == pHead) //找到的是头节点
{
Node *pDel = pHead;
pHead = pHead->Next;
delete pDel;
}
else
{
Node *pCur = pHead;
while (pCur->Next != pSlow)
{
pCur = pCur->Next;
}
pCur->Next = pSlow->Next;
delete pSlow;
}
}
int main()
{
//这里只是单纯的分配节点,不释放节点,要不然篇幅太长了。毕竟节点的分配和释放不是重点。
Node *n1 = new Node(1);
Node *n2 = new Node(5);
Node *n3 = new Node(8);
Node *n4 = new Node(9);
Node *n5 = new Node(12);
Node *n6 = new Node(15);
Node *pHead1 = n1;
n1->Next = n2;
n2->Next = n3;
n3->Next = n4;
n4->Next = n5;
n5->Next = n6;
DelLastKNode(pHead1,6);
Node *pCur = pHead1;
while (pCur)
{
cout << pCur->value <<endl;
pCur = pCur->Next;
}
cout << "hello..." <<endl;
system("pause");
return 0;
}