双链表求倒数第k项

来源:互联网 发布:直销大师软件 编辑:程序博客网 时间:2024/05/17 04:50
#include<iostream>using namespace std;class node{public:    int data;    node *previous;    node *next;};class list{private:    node *last;    node *temp;public:    list():last(NULL),temp(NULL){}    node *create_list();    int getLength();    node *print_data();    ~list();};list::~list (){    node *temp = last;    while (last != NULL)    {        last = last->next;        delete temp;        temp = last;    }}node *list::create_list(){    node *p = new node;    p->previous = NULL;    int x = 0;    while(x >= 0)    {        temp = new node;        cin>>x;        p->data = x;        p->next = temp;        temp->previous = p;        p = temp;        temp = NULL;    }    delete temp;    last = p;    p->next = NULL;    return last;}int list::getLength(){    node *p = last->previous;    int i = -1;    while(p != NULL)    {        p = p->previous;        i++;    }    return i;}node *list::print_data(){    int i;    int n = -1;    cin>>i;    create_list();    node *p = last;    if(i<=0 || i>getLength())    {        cout<<"NULL"<<endl;        return NULL;    }    while(i != n)    {        p = p->previous;        n++;    }    cout<<p->data<<endl;    return last;}int main(){    list l1;    l1.print_data();    return 0;}

双链表求倒数第k项,我没有设计成双循环链表,若想设计成双循环链表,只需头尾相连即可。
原创粉丝点击