标签:article div2 sdn tle find 倒数第k个节点 gen src 注意
/* 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; } };
标签:article div2 sdn tle find 倒数第k个节点 gen src 注意
原文地址:http://www.cnblogs.com/dd2hm/p/7291570.html