首页 > 技术文章 > 面试题-----求单链表的倒数第k个节点

qingergege 2017-11-04 10:53 原文

#include <iostream>
using namespace std;

struct node{
    int value;
    struct node *next;
};

struct node *head;

void insert(struct node * &head,int value)
{
    if(head == NULL)
    {
        head = new struct node;
        head->value = value;
        head->next = NULL;
        return;
    }

    struct node *p = new struct node;
    p->value = value;
    p->next = NULL;

    struct node *q = head;
    while(q->next != NULL)
    {
        q = q->next;
    }

    q->next = p;

}
void find(struct node *head,int k)
{
    if(head == NULL || k <= 0)
        return;
    int i = 0;
    
    struct node *p = head;
    while(p != NULL)
    {
        i++;
        if(i == k)
            break;
        p = p->next;
    }
    struct node *q = head;
    while(p->next != NULL)
    {
        q = q->next;
        p = p->next;
    }
    cout<<q->value<<endl;

    
}



void print(struct node *head)
{
    struct node *p = head;
    while(p != NULL)
    {
        cout<<p->value<<"  ";
        p = p->next;
    }
}

int main()
{
    head = NULL;

    insert(head,1);
    insert(head,3);
    insert(head,5);
    insert(head,9);
    insert(head,11);
    insert(head,16);
    insert(head,18);
    insert(head,6);
    insert(head,10);
    insert(head,12);
    insert(head,13);
    insert(head,15);
    cout<<"链表:";
    print(head);
    int k = 3;
    cout<<"的到数第"<<k<<"个节点为:";
    find(head,k);

    return 0;
}

 

推荐阅读