//查找链表中倒数第k个节点
#include <iostream>
using namespace std;
//定义链表节点结构
struct ListNode
{
int data;
ListNode *next;
};
//创建不带头结点的单链表
void createList(ListNode *&Head)
{
int num = 0;
int flag = 0;
ListNode *p = NULL;
cin >> num;
Head = (ListNode *)malloc(sizeof(ListNode));
while(num != 0)
{
if(flag == 0)
{
Head->data = num;
Head->next = NULL;
flag = 1;
p = Head;
}
else
{
ListNode *cur = (ListNode *)malloc(sizeof(ListNode));
cur->data = num;
cur->next = NULL;
p->next = cur;
p = cur;
}
cin >> num;
}
// return temp;
}
//打印链表
void printList(ListNode *Head)
{
if(Head == NULL)
{
cout << "Head empty"<<endl;
return ;
}
ListNode *p = Head;
while(p != NULL)
{
cout << p->data <<" ";
p = p->next;
}
}
//找到倒数第k个,也就是整数第n-k-1个
ListNode *FindK1(ListNode *Head,unsigned int k)
{
if(Head == NULL)
{
return NULL;
}
ListNode *pCur = Head;
//定义nNum,记录链表长度
unsigned int nNum = 0;
//求取链表长度
while(pCur->next != NULL)
{
pCur = pCur->next;
nNum++;
}
//
if(nNum < k)
{
return NULL;
}
pCur = Head;
for(unsigned int i=0; i < nNum-k; i++)
{
pCur = pCur->next;
}
return pCur;
}
//采用两个指针,一前一后,相隔k个位置。
ListNode *FindK2(ListNode *Head,unsigned int k)
{
if(Head == NULL)
{
return NULL;
}
ListNode *pHead = Head;
ListNode *pBehind = NULL;
for(unsigned int i=0; i<k; ++i)
{
if(pHead->next != NULL)
{
pHead = pHead->next;
}
else
{
return NULL;
}
}
pBehind = Head;
while(pHead->next != NULL)
{
pHead = pHead->next;
pBehind = pBehind->next;
}
return pBehind;
}
//测试用例
void main()
{
ListNode *List = NULL;
cout << "创建链表:";
createList(List);
cout << "链表元素:";
printList(List);
ListNode *p = FindK1(List,4);
cout << endl <<"倒数第四个:" <<p->data <<endl;
ListNode *q = FindK2(List,5);
cout << "倒数第五个:" <<q->data <<endl;
}
运行结果:
创建链表:1 2 3 4 5 6 7 8 9 0
链表元素:1 2 3 4 5 6 7 8 9
倒数第四个:5
倒数第五个:4
请按任意键继续. . .