C:单链表的循环和递归实现

两天前,C语言课上讲了单链表的实现,下课回到寝室立马开始动手写,中间还是出了几个BUG,不过最终首先用循环实现了最简单的单链表

#include <stdio.h>
#include <Windows.h>
#include <stdlib.h>
#include <malloc.h>

typedef struct node
{
    int data;
    struct node *next;
}Node;

Node *Creat();//链表函数声明

int main()
{
    Node *h, *p, *t;
    h = Creat();//头指针获取
    p = t = h->next;//获取第二个结点
    while (t->next!= NULL)
    {
        printf(" >%d", t->data);
        p = t;
        t = t->next;
        free(p);//释放输出过的结点的内存
    }
    system("pause");
}

Node *Creat()  
{
    Node *h, *p, *r;
    int x;
    h = p = r = NULL;//可有可无
    scanf_s("%d", &x);
    h = (Node*)malloc(sizeof(Node));//申请头结点
    h->next = NULL;//头结点内自引用结构初始化
    p = (Node*)malloc(sizeof(Node));//申请第二个结点
    while (1)
    {
        if (h->next== NULL)
            h->next = p;//指向第二个结点
        r = (Node*)malloc(sizeof(Node));//申请新的结点
        p->data = x;
        p->next = r;
        r->next = NULL;//默认认为此时结点为尾结点
        p = r;
        scanf_s("%d",&x);
        if (x == -1)
            break;
    }
    return h;
}

**之后我尝试用递归实现,发现对于建立单链表而言递归比循环简单
注:我至今没有搞明白斐波那契数列的递归算法(哭)**

#include <stdio.h>
#include <malloc.h>
#include <Windows.h>

typedef struct Node
{
    int data;
    struct Node *next;
}node;

node *Creat(int x,node *h);

int main()
{
    int x;
    node *h, *p, *t;
    h = (node*)malloc(sizeof(node));
    h->next = NULL;
    scanf_s("%d", &x);
    Creat(x, h);
    p = t = h->next;
    while(t!= NULL)
    {
        printf(" >%d", t->data);
        p = t;
        t = t->next;
        free(p);
    }
    system("pause");
}

node *Creat(int x,node *h)//递归算法
{
    if (x == -1)
        return NULL;//递归终止
    int a;
    node *p;
    p = (node*)malloc(sizeof(node));
    h->next = p;
    p->data = x;
    p->next = NULL;
    scanf_s("%d", &a);
    Creat(a, p); //开始递归
    return p;

}

注:今天有同学问我一道二级考试的改错题,按照日常习惯,看完题直接从头开始写算法。题目是利用递归求斐波那契数列数列的第n项,结果写的我怀疑人生,看了二级考试的代码后也不能完全理解递归过程,果然我不适合学编程么(哭)

int fun(int n)
{
    if (n <= 1)
        return n;
    else
        return (fun(n - 1) + fun(n - 2));

}

猜你喜欢

转载自blog.csdn.net/kongming07/article/details/78790910
今日推荐