zoukankan      html  css  js  c++  java
  • 面试题-----求单链表的倒数第k个节点

    #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;
    }
  • 相关阅读:
    事务
    排序算法
    二维数组中的查找
    在Linux中安装Matlab
    null和“”的区别
    【学习笔记】〖九度OJ〗题目1433:FatMouse
    【学习笔记】〖九度OJ〗题目1464:Hello World for U
    year:2017 month:8 day:1
    year:2017 month:07 day:31
    year:2017 month:7 day:27
  • 原文地址:https://www.cnblogs.com/qingergege/p/7782723.html
Copyright © 2011-2022 走看看