题解 | #输出单向链表中倒数第k个结点#

输出单向链表中倒数第k个结点

https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d

这道题很简单 写题解主要是为了能够练习双向链表的处理
需要注意的是 在只有一个元素的时候,需要对tail尾部指针进行特殊处理,使得head=tail
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <sstream>
#include <stack>
#include <map>
using namespace std;
typedef long long ll;

struct node{
    int data;
    node *next;
    node *pre;
};

int main()
{
    int n,i,j;
    while(cin>>n){
    int t,k;

    node *head,*p,*q,*tt,*tail;
    cin>>t;

    head=new node();
    head->data=t;
    head->next=NULL;
    head->pre=NULL;


    p=head;
    for(i=2;i<=n;i++){
        cin>>t;
        q=new node();
        q->data=t;
        q->next=NULL;
        q->pre=p;
        p->next=q;
        p=p->next;
    }
    tail=q;

    if(n==1) tail=head;

    i=1;
    cin>>k;
    tt=tail;
    while(i!=k){
        i++;
        tt=tt->pre;
    }

    cout<<tt->data<<endl;
    }
    return 0;
}





全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务