码迷,mamicode.com
首页 > 其他好文 > 详细

链表中获取倒数第K个结点

时间:2018-05-01 20:31:42      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:pac   insert   空指针   span   class   str   ted   space   auth   

/*
 * 链表中查找倒数第K个结点.cpp
 *
 *  Created on: 2018年5月1日
 *      Author: soyo
 */
#include<iostream>
using namespace std;
struct Node
{
    int num;
    Node * next;
};
Node * creat()
{
    Node *head=NULL;
    head=new Node;
    head->num=9;
    head->next=NULL;
    return head;
}
Node * insert(Node *head,int x)
{
    Node *p,*p2;
    p=new Node;
    p->num=x;
    p->next=NULL;
    p2=head;
    while(p2->next!=NULL)
    {
        p2=p2->next;
    }
    p2->next=p;
    return head;
}
void println(Node *head)
{
    //cout<<head->next->next->num;
    if(head==NULL)
        return;
    while(head!=NULL)
    {
        cout<<head->num<<" ";
        head=head->next;
    }
}
Node* find_k_Num(Node *head,int k)   //链表倒数第K个节点的值
{
    if(head==NULL||k==0)
        return NULL;
    Node *p1=NULL,*p2=NULL;
    p1=head;
    for(int i=0;i<k-1;i++)
    {
        if(p1->next!=NULL)      //防止 K比链表的长度还大 出现访问空指针
            p1=p1->next;
        else
            return NULL;
    }
    p2=head;
    while(p1->next!=NULL)
    {
        p1=p1->next;
        p2=p2->next;
    }
    return p2;

}
int main()
{
    int a[]={1,2,3,4,5};
    Node *head;
    head=creat();
    for(int i=0;i<5;i++)
    {
        head=insert(head,a[i]);
    }
   println(head);
   int x;
   cin>>x;
   Node *findNode=find_k_Num(head,x);
   cout<<"倒数第"<<x<<"个结点为:"<<findNode->num<<endl;

}

结果:

9 1 2 3 4 5

倒数第3个结点为:

 

链表中获取倒数第K个结点

标签:pac   insert   空指针   span   class   str   ted   space   auth   

原文地址:https://www.cnblogs.com/soyo/p/8976645.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!