zoukankan      html  css  js  c++  java
  • CCI_Q2.2

    本文参考该作者文章当作编程笔记:
    
    作者:Hawstein
    出处:http://hawstein.com/posts/ctci-solutions-contents.html

    Q:实现一个算法从一个单链表中返回倒数第n个元素。

    思路:

    findNthRecursion(link):递归的调用单链表的下一个节点,直到到达链表的尾部。此时,开始计数,直到到倒数第nn个数时,返回此时的h,即pp。

                  缺点是需要定义两个全局变量。

    link findNthToLast(link,int):定义两个指针p和q,使p和q之间差距n个距离,当p指向NULL时,q就指向了倒数第n个数。

    Talk is cheap,Show me CODE:

    • list.h接口
    1 typedef struct node *link;
    2 typedef int itemType;
    3 struct node{itemType item;link next;};
    4 void initNodes(link,itemType [],int);
    • list.c实现
    #include<stdlib.h>
    #include"list.h"
    void initNodes(link h,itemType s[],int n)
    {
        link p=h;
        int i;
        for(i=0;i<n;i++)
        {
            p->next=malloc(sizeof(struct node));
            p=p->next;
            p->item=s[i];
            p->next=NULL;
        }
    }
    • 客户程序
     1 #include<stdio.h>
     2 #include"list.h"
     3 #define N 10
     4 struct node head;
     5 link pp=NULL;
     6 int nn;
     7 void findNthRecursion(link h)
     8 {
     9     if(h==NULL)return;
    10     findNthRecursion(h->next);
    11     if(nn==1)pp=h;
    12     nn--;
    13 }
    14 link findNthToLast(link h,int n)
    15 {
    16     if(h==NULL||n<1)return NULL;
    17     link p=h,q=h;
    18     while(n>0&&p)
    19     {
    20         p=p->next;
    21         n--;
    22     }
    23     if(n>0)return NULL;
    24     while(p)
    25     {
    26         p=p->next;
    27         q=q->next;
    28     }
    29     return q;
    30 }
    31 int main()
    32 {
    33     int s[N]={1,2,3,4,5,6,7,8,9,0};
    34     initNodes(&head,s,N);
    35     link p=findNthToLast(&head,6);
    36     if(p)printf("%d
    ",p->item);
    37     nn=6;
    38     findNthRecursion(&head);
    39     if(pp)printf("%d
    ",pp->item);
    40     return 0;
    41 }
  • 相关阅读:
    webpack基础
    LeetCode232. 用栈实现队列做题笔记
    mysql 时间加减一个月
    leetcode 1381. 设计一个支持增量操作的栈 思路与算法
    LeetCode 141. 环形链表 做题笔记
    leetcode 707. 设计链表 做题笔记
    leetcode 876. 链表的中间结点 做题笔记
    leetcode 143. 重排链表 做题笔记
    leetcode 1365. 有多少小于当前数字的数字 做题笔记
    LeetCode1360. 日期之间隔几天 做题笔记
  • 原文地址:https://www.cnblogs.com/jhooon/p/3582546.html
Copyright © 2011-2022 走看看