双链表求倒数第k项

#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项,我没有设计成双循环链表,若想设计成双循环链表,只需头尾相连即可。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值