zoukankan      html  css  js  c++  java
  • 查找链表倒数第k个数

    题目:输入一个单向链表,输出该链表中倒数第k个结点。链表的倒数第0个结点为链表的尾指针。

    链表结点定义如下:

    struct ListNode
    {
        int m_nKey;
        ListNode* m_pNext;
    };

    答:

    #include "stdafx.h"
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    struct ListNode
    {
        int m_nKey;
        ListNode* m_pNext;
    };
    
    //构造链表
    void CreateList(ListNode *&pHead)
    {
        fstream fin("list.txt");
        ListNode *pNode = NULL;
        ListNode *pTmp = NULL;
        int data;
        fin>>data;
        while (data)
        {
            pNode = new ListNode;
            pNode->m_nKey = data;
            pNode->m_pNext = NULL;
            if (NULL == pHead)
            {
                pHead = pNode;
                pTmp = pNode;
            }
            else
            {
                pTmp->m_pNext = pNode;
                pTmp = pNode;
            }
    
            fin>>data;
        }
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        ListNode *pHead = NULL;
        CreateList(pHead);
        ListNode *p = pHead;
        ListNode *q = pHead;
        int k = 5;
        for (int i = 0 ; NULL != p && i < k; i++)
        {
            p = p->m_pNext;
        }
        if (NULL == p)
        {
            return;
        }
        while (NULL != p)
        {
            p = p->m_pNext;
            q = q->m_pNext;
        }
        cout<<q->m_nKey<<endl;
        cout<<endl;
        return 0;
    }

    运行界面如下:

    建造链表的list.txt文件如下:

    12 11 10 9 8 7 6 5 4 3 2 1 0
  • 相关阅读:
    如何将网站升级为HTTPS协议?
    hashmap:cr:csdn
    HashMap的底层原理 cr:csdn:zhangshixi
    servlet
    泛型,反射
    线程

    集合
    java基础题
    我的博客网址
  • 原文地址:https://www.cnblogs.com/venow/p/2653440.html
Copyright © 2011-2022 走看看