剑指offer 链表中倒数第k个结点

来源:互联网 发布:supply chain 知乎 编辑:程序博客网 时间:2024/05/09 21:50

题目描述:
输入一个链表,输出该链表中倒数第k个结点。
(hint: 请务必使用链表。)

思路:
单向链表,故不能倒着来,我们可以定义两个指针p1,p2,对于倒数第k个,我们先令p1走k步,然后两个指针一起走,如果p1到了结尾,则p2所对应的值就是所求。

#include <cstdio>using namespace std;typedef struct Node{    int val;    Node *next;    Node(int val = -1) : val(val), next(NULL) {}}*pNode;class List{private:    pNode Head;    pNode Tail;    int List_Size;    void Delete_List(pNode);public:    void Delete_Content();    int Find(int x);    void Insert_Node(int x);    List();    ~List();};void List::Insert_Node(int x){    Node *node = new Node(x);    List_Size++;    this->Tail->next = node;    this->Tail = node;}int List::Find(int x){    if(x <= 0 || x > List_Size)        return -1;    pNode p1 = this->Head->next, p2 = this->Head->next;    for(int i = 0; i < x; i++)        p1 = p1->next;    while(p1){        p1 = p1->next;        p2 = p2->next;    }    return p2->val;}void List::Delete_Content(){    pNode p = this->Head->next;    while(p){        pNode child = p->next;        delete p;        p = child;    }    this->Head->next = NULL;    this->Tail = this->Head;    List_Size = 0;}void List::Delete_List(pNode node){    if(node){        Delete_List(node->next);        delete node;    }}List::List(){    Head = Tail = new Node();    List_Size = 0;}List::~List(){    Delete_List(this->Head);}int main(){    int n, x;    int v;    List *list = new List;    while(scanf("%d%d", &n, &x) != EOF){        for(int i = 0; i < n; i++){            scanf("%d", &v);            list->Insert_Node(v);        }        int ans = list->Find(x);        if(ans == -1)            printf("NULL\n");        else            printf("%d\n", ans);        list->Delete_Content();    }    delete list;    return 0;}
0 0
原创粉丝点击