您的位置:首页 > 职场人生

程序员面试金典: 9.2链表 2.2找出单向链表中倒数第k个节点

2016-12-21 10:05 369 查看
#include <iostream>
#include <stdio.h>

using namespace std;

/*
问题:实现一个算法,找出单项链表中倒数第k个结点
分析:这个应该设置两个指针,
举个例子:一共6个节点,找到倒数第2个节点,
实际上找到的就是第5个节点= N - k + 1
最好的方式就是,一个指针找到第5个节点的时候,另一
指针刚好到第6个节点
1 2 3 4 5 6
第一个指针走到N-k+1时,第二个指针走到N
两者相差步数=N - (N-k+1) = k - 1,也就是第一个指针
先走(k-1)步后,两个指针一起走
即先走1步
N=7,k=3时

输入:
7(总节点个数) 3(k,倒数第几个节点)
1 2 3 4 5 6 7
输出:
5

关键:
1 倒数第k个节点=正数第(N-k+1)个节点
第二个指针走到N-k+1时,第一个指针走到N
2 第一个指针比第二个指针提前走= N - (N-k+1)= k-1步
3 1 <= k <= N,如果k>N,则无法成立
*/

typedef struct Node
{
int value;
Node* pNext;
}Node;

//构建连边,按照尾插法来做,返回节点值到出现次数的映射
void buildList(int* pArray , Node* head , int num)
{
if(pArray == NULL)
{
return;
}
if(head == NULL)
{
return;
}

//尾插法: 保留最后一个结尾节点,将新生成的节点插入在结尾节点,并令结尾节点为当前节点
Node* pLast = head;
//int num = sizeof(pArray) / sizeof(int);
for(int i = 0 ; i < num ; i++)
{
int value = *(pArray + i);
Node* pNode = new Node();
pNode->value = value;
pLast->pNext = pNode;
pLast = pNode;
}
}

Node* findKNode(Node* pHead , int k , int n)
{
if(NULL == pHead)
{
return NULL;
}
if( k > n || k < 1)
{
return NULL;
}

//设置两个指针,第一个指针先走k-1步,然后两个指针一起走,注意头指针不算
Node* pFast = pHead;
int count = 0;
while(pFast)
{
if(count == k-1)
{
break;
}
count++;
pFast = pFast->pNext;
}
Node* pSlow = pHead;
while(pFast->pNext != NULL)
{
pFast = pFast->pNext;
pSlow = pSlow->pNext;
}
return pSlow;
}

void printList(Node* pHead)
{
if(NULL == pHead)
{
return;
}
Node* pNode = pHead->pNext;
while(pNode)
{
cout << pNode->value << " ";
pNode = pNode->pNext;
}
cout << endl;
}

void releaseList(Node* pHead)
{
if(NULL == pHead)
{
return;
}
Node* pNode = pHead->pNext;
Node* pPrevious = pHead;
while(pNode)
{
Node* pDeleteNode = pNode;
pPrevious->pNext = pNode->pNext;
pNode = pNode->pNext;
pPrevious = pPrevious->pNext;
delete pDeleteNode;
}
//删除头结点
delete pHead;
}

int main(int argc, char* argv[])
{
int n , k;
while(cin >> n >> k)
{
int* pArr = new int
;
for(int i = 0 ; i < n ; i++)
{
cin >> pArr[i];
}
Node* pHead = new Node();
buildList(pArr , pHead , n);
Node* pNode = findKNode(pHead , k , n);
cout << pNode->value << endl;
//printList(pHead);
releaseList(pHead);
}
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: