zoukankan      html  css  js  c++  java
  • 链表中倒数第k个节点

    #include <iostream>
    
    using namespace std;
    
    struct ListNode
    {
        int val;
        ListNode *next;
        ListNode(int x):val(x),next(NULL){};
    } ;
    
    ListNode* daoshu(ListNode *head,int k)
    {
        if(head==NULL||k==0)
            return NULL;
        ListNode *p1=head;
        ListNode *p2=head;
        for(;k>1;k--)
        {
            if(p1->next!=NULL)
                p1=p1->next;
            else 
                return NULL;
        }
    
        while(p1->next!=NULL)
        {
            p1=p1->next;
            p2=p2->next;
        }
        return p2;
    }
    int main()
    {
        ListNode *head=new ListNode(0);
        ListNode *p=head,*q;
        int a[5]={1,2,3,4,5};
        for(int i=0;i<=4;i++)
        {
            ListNode *newnode=new ListNode(a[i]);
            p->next=newnode;
            p=newnode;
        }
        p=head;
        while(p!=NULL)
        {
            cout<<p->val;
            p=p->next;
        }
    
        q=daoshu(head,2); //倒数第2个
        cout<<endl<<q->val;
        return 0;
    }
  • 相关阅读:
    cygwin mysql forget root password
    emacs 复制粘贴的正确姿势
    yarn
    mysql 和 postgresql 区别
    hdfs
    spark
    hbase
    kafka
    flume
    java jar
  • 原文地址:https://www.cnblogs.com/home123/p/7444579.html
Copyright © 2011-2022 走看看