算法实现:返回单链表的倒数第pos个节点
生活随笔
收集整理的這篇文章主要介紹了
算法实现:返回单链表的倒数第pos个节点
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
//騰訊的面試題 2015-04-14
//轉載自:http://blog.chinaunix.net/uid-23629988-id-2169046.html?page=2
#include <iostream>
#include <ctime>
#include <vector>
using namespace std;//建立一個鏈表
struct Node
{int data;Node *next;
};//函數功能創建一個鏈表,并順序的輸出所有值
void CrateLink(Node *&head ,const int n)
{head = new Node;head->next = NULL;head->data = rand()%10000;Node *p ,*pr;p = head;pr = p;int i = n;i --;while(i--){p->next = new Node;pr = p->next;p = pr;pr->next = NULL;pr->data = rand()%10000;}p = head;while(NULL != p ){cout << p->data << " ";p = p->next;}cout << endl;}
/*
參數解釋head 表示鏈表的頭pos 表示倒數第pos個值d 表示包含返回值的節點算法的思想就是 利用兩個指針 ret 和 head,
這兩個指針之間的關系是 head指向的節點大于ret指向的節點 pos個值,即兩個指針相差pos個節點
當head指向最后一個值時,ret就為倒數第pos個節點
*/void find(Node *head,int pos,Node &d) //找到倒數第pos個值 // 注意pos的值和數組的下標的意義是一樣的,第0個就是array[n]
{int i = 0;Node *ret = head;while(i<pos && head != NULL) //head向后移動pos個節點,同時檢查鏈表的值是否滿足個數{head = head->next;i++;}if(head == NULL ) //檢查鏈表是否有 倒數第 pos個節點return ;while(head->next != NULL){ret = ret->next;head = head->next;}d.data = ret->data;
}
int main()
{Node *head =NULL ; CrateLink(head ,10);Node d;find(head,2,d); //顯示倒數第 2 個節點cout << d.data << endl;return 0;
}
總結
以上是生活随笔為你收集整理的算法实现:返回单链表的倒数第pos个节点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++中的STL--基本概念
- 下一篇: Leetcode unique-path