鏈表中獲取倒數第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;

}

結果:ios

9 1 2 3 4 5

倒數第3個結點爲:
相關文章
相關標籤/搜索