链表中的倒数第k个结点

题目描述

输入一个链表,输出该链表中倒数第k个结点。
 
基本思想:定义两个指针a,b分别指向头节点, a指针先向前走 k-1步(注意:因为倒数节点是从倒数第一个结点开始的,而不是零),然后a指针和b指针一起向前移动,
     直到a->next == NULL。此时,b指针所指向的结点。即为倒数第K个结点。
 
边界条件:1.输入的pListHead为空指针的情况;
       2.输入的以pListHead为头结点的链表的节点总数少于K的情况;
     3.输入K为0的情况。
#include <iostream>
#include <algorithm>
#include "string.h"
#include "stdio.h"
#include <vector>
#include <deque>
#include<stack>
using namespace std;

struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class List{
public:

    ListNode* CreatList(int* arr,int len)
    {
        int val;
        ListNode* pHead = new ListNode(arr[0]);
        ListNode* pCurrent=NULL;
        ListNode* rear = pHead;
        int count = 1;
        while(count<len)
        {
            ListNode* pCurrent = new ListNode(arr[count]);
            rear->next = pCurrent;
            rear = pCurrent;
            count++;
        }
        rear->next = NULL;
        return pHead;
    }
    void ShowList(ListNode* pHead)
    {
       while(pHead)
       {
           cout<<pHead->val<<" ";
           pHead = pHead->next;
       }
       cout<<endl;
    }
    ListNode* GetLastNode(ListNode* pHead)
    {
        ListNode* pNode = pHead;
        while(pNode->next!=NULL)
        {
            pNode=pNode->next;
        }
        return pNode;
    }
};
class Sort{
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {

        if(pListHead == NULL||k==0)
            return NULL;
        ListNode* pNode = pListHead;
        ListNode* p = pListHead;
        int count = 0;

        pNode=pListHead;
        for(int i=0;i<k-1;i++)
        {
            if(pNode->next!=NULL)
                pNode = pNode->next;
            else
                return NULL;
        }
        while(pNode->next!=NULL)
        {
            p = p->next;
            pNode=pNode->next;
        }
        return p;
    }
};
int main()
{
    int array[]={3,4,5,1,2,8,7};
    List list;
    Sort sort;
    ListNode* pHead = list.CreatList(array,sizeof(array)/sizeof(array[0]));

    list.ShowList(pHead);
    ListNode* pNode = sort.FindKthToTail(pHead,7);
    cout<<pNode->val<<endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/omelet/p/6653557.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值