单行链表寻找倒数第k个节点

来源:互联网 发布:eia数据公布 时间 编辑:程序博客网 时间:2024/06/05 21:02

/**
*题目介绍:给出一个单向链表,输出该链表的倒数第k个节点
*           设尾节点开始从0编号
*/

解题思路:两个指针往后移动,一定要注意边界的处理情况。此处我设置了一个头指针,头指针不存数据,仅仅作为头标志。


/***题目介绍:给出一个单向链表,输出该链表的倒数第k个节点*           设尾节点开始从0编号*/#include <iostream>#include <stdlib.h>#include <cstdio>using namespace std;struct node{    int value;    struct node * next;} *head;inline void nodeinit(struct node *n){    n->next = NULL;    n->value = 0;}void creatnodelist(){    //头指针 应该首先分配地址    if(head == NULL)        head = (struct node *)malloc(sizeof(struct node));    nodeinit(head);    int v;    struct node * pt = head;    scanf("%d",&v);    while(v)    {        if(pt->next == NULL)            pt->next = (struct node *)malloc(sizeof(struct node));        pt=pt->next;        nodeinit(pt);        pt->value = v;        //cout<<pt->value ;        scanf("%d",&v);    }}int findLastK(int k){    struct node * p1=head;    struct node * p2=head;    while(k--)        p1=p1->next;    p1=p1->next;    while(p1 != NULL)        p1=p1->next,p2=p2->next;    return p2->value;}void print(){    struct node * p=head->next;    while(p!=NULL)        cout<<p->value<<"  ",p=p->next;}int main(){    cout << "create node list:" << endl;    creatnodelist();    print();    int k;    cout<<"\ninput k :";    scanf("%d",&k);    cout<<"\nthe last "<<k<<" node is : "<<findLastK(k)<<endl;    return 0;}