剑指offer面试题22--链表倒数第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) {
        if(k==0||pListHead==nullptr)          //传入的链表实参不能是空。k不能等于0
            return NULL;
        
        ListNode* pHead=pListHead;
        ListNode* pBehind=pListHead;
        
        for(int i=1;i<=k-1;++i)
        {
            if(pHead->next!=nullptr)        //防止出现链表的节点数目少于k出现不可预知的异常
            {
                pHead=pHead->next;
            }
          
             else 
                 return nullptr;
            
        }
        
         while(pHead->next!=nullptr)
            {
                pHead=pHead->next;      //第一次写的时候写成了pHead++;,从高考到应聘,有时候比的就是应聘比的就是细节
pBehind=pBehind->next; } return pBehind; } };

也有一种算法,要遍历两趟链表,第一趟求出链表节点个数length,第二趟从头结点(算第一个节点)开始遍历到length-k+1个节点,就是待求节点。但是这种方法不如上面实现的,只需遍历一趟链表

上述算法可以实现仅仅遍历一趟链表

 

猜你喜欢

转载自blog.csdn.net/qq_34793133/article/details/80960532