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

/*
 * 链表中查找倒数第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个结点为:

猜你喜欢

转载自www.cnblogs.com/soyo/p/8976645.html