首页 > 代码库 > 输出链表的倒数第K个值
输出链表的倒数第K个值
题目描述
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { int len=0; ListNode *p=pListHead; while(p!=NULL) { len++;//算出链表长度 p=p->next; } if(k>len || k<0) return NULL;//两种特殊情况 int i=1; //设置一个变量 p=pListHead;//p重置为起点 while(i<len-k+1) {//直到整数第len(list)-k个位置,进行最后一层循环,到达 p=p->next; i++; } return p; } };
http://blog.csdn.net/hhh3h/article/details/20832387
另一种思路:
class Solution { public: ListNode* FindKthToTail(ListNode* p_head, unsigned int k) {//找到链表的倒数第K个节点 //if(k==0)特殊处理,k小于链表长度,特殊处理 if (k==0 || p_head == nullptr) return nullptr; ListNode* first = p_head; ListNode* second = p_head; for (int i = 0; i < k - 1; i++) { if(first->next== nullptr) return nullptr; first = first->next; } while (first->next != nullptr) { first = first->next; second = second->next; } return second; } };
https://m.baidu.com/from=2001a/bd_page_type=1/ssid=c534dcb1bcccd0f8341c/uid=0/pu=usm%401%2Csz%40320_1003%2Cta%40iphone_2_5.1_1_11.6/baiduid=CC7E451183AFD2E2A766A5E6F241C7F9/w=0_10_/t=iphone/l=3/tc?ref=www_iphone&lid=13759879435784551619&order=2&fm=alop&tj=www_normal_2_0_10_title&vit=osres&m=8&srd=1&cltj=cloud_title&asres=1&nt=wnor&title=求链表中的倒数第K个节点-General_up-博客园&dict=30&w_qd=IlPT2AEptyoA_ykx5fEcv4a6DFlPc7onxiUXo48TrfK-&sec=23004&di=c048fb26097f7fab&bdenc=1&tch=124.332.162.435.1.248&nsrc=http://www.mamicode.com/IlPT2AEptyoA_yixCFOxXnANedT62v3IEQGG_ytK1DK6mlrte4viZQRARTL6NWmXH9jgtCPQpt5Ywk_e0G5o7hVDwvQkfjS&eqid=bef4e971a2240000100000005985ba10&wd=&clk_info=%7B"srcid"%3A"1599"%2C"tplname"%3A"www_normal"%2C"t"%3A1501936158515%2C"sig"%3A"12735"%2C"xpath"%3A"div-div-div2-a-p-em"%7D&sfOpen=1&sfr_fb=0&qq-pf-to=pcqq.c2c
输出链表的倒数第K个值