输出链表中倒数第m个元素
来源:互联网 发布:免费的视频剪辑软件 编辑:程序博客网 时间:2024/05/29 04:47
// 输出链表中倒数第m个元素.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>#include <algorithm>struct Node{ int value; struct Node *next; };Node *createLinklist(int length){ Node *head, *last, *p; head = (Node *)malloc(sizeof(Node)); last = (Node *)malloc(sizeof(Node)); for(int i=0; i<length; i++) { p = (Node *)malloc(sizeof(Node)); p->value = i; p->next = NULL; if(i == 0) head->next = p; last->next = p; last = p; } return head->next;}Node * FindMToLastNode(Node * pHead, int m){// 查找到第m个元素Node * pCurrent = pHead;for (int i = 0; i < m; ++i){if (pCurrent){pCurrent = pCurrent->next;}else{return NULL;}}// 一起继续遍历到链表尾部,// 现在pFind和pCurrent之间间隔了m个元素,// 所以,当pCurrent遍历到尾部的时候,// pFind就到了倒数第m个元素的位置上.Node* pFind = pHead;while (pCurrent){pFind = pFind->next;// 间隔m个元素pCurrent = pCurrent->next;}return pFind;} int main(){Node *list = createLinklist(10); std::cout << FindMToLastNode(list, 3)->value << std::endl;return 0;}