链表中倒数第k个结点

输入一个链表,输出该链表的倒数第k个结点。设尾结点为倒数第1个结点,例如一个链表

从头到尾结点的值依次为1、2、3、4、5、6,则倒数第三个结点为4。

// ConsoleApplication3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "iostream"
using namespace std;
struct ListNode
{
ListNode* next;
int data;
ListNode()
{
next=NULL;
data=0;

}
};

//找到链表倒数第K个点;
ListNode *FindLastNode(ListNode*head,int k)
{
if(head==NULL||k<1)
return NULL;
ListNode* ret=head;
for(int i=1;i!=k;++i)
{
if(head->next!=NULL)
head=head->next;
else
return NULL;

}
while (head->next!=NULL)
{
head=head->next;
ret=ret->next;
}
return ret;
}

//创建链表添加结点;
ListNode *CreateNode(ListNode* head,int data)
{
ListNode *fist=head;

while (head!=NULL)
{
if(head->next==NULL)
{
ListNode *tem=new ListNode();
tem->data=data;
head->next=tem;
break;
}
head=head->next;
}
return fist;
}
int main(int argc, char* argv[])
{
ListNode *head=new ListNode();
head=CreateNode(head,1);
head=CreateNode(head,2);
head=CreateNode(head,3);
head=CreateNode(head,4);
head=CreateNode(head,5);
head=CreateNode(head,6);
head=CreateNode(head,7);
ListNode *tem=head;
while (head!=NULL)
{
cout<<head->data<<endl;
head=head->next;
}
int k=4;
cout<<"倒数第"<<k<<"个是:"<<FindLastNode(tem,k)->data<<endl;
getchar();
return 0;
}