• Link List


    At first, i prepared to go through 《the introduction to algorithm》 ,however , i found some part of the book is difficult to understand; what’s more , i can’t borrow the book in the library. Then i found another book, 《algorithm in C》,which reveal most basic idea of some classical algorithm, so i decide to read this book firstly.

    example 1:josephus funciton

    #include<stdlib.h>
    #include<stdio.h>
    typedef struct node* link;
    struct node
    {
        int item;
        link next;
    };
    
    int main(int argc,char *argv[])
    {
        int i, N, M;
        scanf("%d%d",&N,&M);
        node *t = new node,*x;
        x = t;
        t->item = 1;
        t->next = t;
        for (i = 2; i <= N; i++)
        {
            x->next = new node;
            x = x->next;
            x->item = i;
            x->next = t;
        }
        while (x != x->next)
        {
            for (i = 1; i < M; i++)
            {
                x = x->next;
            }
            x->next = x->next->next;
            N--;
        }
        printf("%d
    ",x->item);
    }

    example2: reverse link list

    #include<stdlib.h>
    #include<stdio.h>
    typedef struct node* link;
    struct node
    {
        int item;
        link next;
        node()
        {
            next = NULL;
        }
    };
    
    link reverse(link x)
    {
        /*
        将y后节点的指针保存在t中,然后将y的链接指向r,再使r移到y,y移到t
        */
        link t, y = x, r = NULL;
        while (y != NULL)
        {
            t = y->next;
            y->next = r;
            r = y;
            y = t;
        }
        return r;
    }
    
    int main(int argc,char *argv[])
    {
        int i, N, M;
        scanf("%d%d",&N,&M);
        node *t = new node,*x,*head;
        x = t;
        head = t;
        t->item = 1;
        t->next = t;
        for (i = 2; i <= N; i++)
        {
            x->next = new node;
            x = x->next;
            x->item = i;
        }
        node *newhead = reverse(head);
        while (newhead != NULL)
        {
            printf("%d ",newhead->item);
            newhead = newhead->next;
        }
    }
  • 相关阅读:
    二叉树中和为某一值的路径
    二叉搜索树的后序遍历序列(important!)
    从上往下打印二叉树
    最小的k个数(important!)
    扑克牌顺子
    栈的压入、弹出序列(important!)
    和为s的连续正数序列(important!)
    数组中只出现一次的数字
    fgets()函数以及fputs()函数
    C语言中的指针
  • 原文地址:https://www.cnblogs.com/maverick-fu/p/3994605.html
Copyright © 2020-2023  润新知