程序员面试金典: 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; }
相关文章推荐
- Activity返回数据给上一个Activity(非常重要,面试必备)
- Java的Exception和Error面试题15问15答
- 程序员面试金典: 9.2链表 2.1移除未排序链表中重复的节点
- 分享大牛开发经验,浅谈java程序员职业规划
- 分享大牛开发经验,浅谈java程序员职业规划
- 职场指导
- 关于程序员们的一些有趣的事实,你中招了吗?
- 职场可能犯下的错误
- 你在职场可能犯下的错误
- 你在职场可能犯下的最大错误
- 理想的程序员
- 很神奇的一些面试题
- Java面试题全集(上)
- 值得程序员一看的 8 个冷门小知识
- 任性!我赢职场双旦钜惠万元课程免费学
- 面向程序员的数据挖掘指南(六)
- OSChina 周三乱弹 ——程序员、魔法师和麻瓜
- 代码面试最常用的10大算法
- 浅谈程序员的数学修养
- 程序员面试宝典——子串判断