zoukankan      html  css  js  c++  java
  • Linked List in C (3Sorted List)

    #include<stdio.h>
    #include<stdlib.h>
    #include<math.h>
    
    typedef struct _node
    {
        int data;
        struct _node *next;
    }node;
    
    void insertNodeSorted(node **head, node *newNode);
    void printList(node *head);
    void deleteList(node **head);
    
    void insertNodeSorted(node **head, node *newNode)
    {
        if(*head == NULL)
        {
            *head = newNode;
        }
        else if( (*head)->data > newNode->data )
        {
            newNode->next = *head;
            *head = newNode;
        }
        else
        {
            node *temp = *head;
            while( (temp->next != NULL) && (temp->next->data < newNode->data))
            {
                temp = temp->next;
            }
            newNode -> next = temp -> next;
            temp -> next = newNode;
        }
    }
    
    void printList(node *head)
    {
        int i = 0;
        node *temp = head;
        while(temp != NULL)
        {
            printf("data in node %d is: %d \n", i, temp->data);
            temp = temp->next; 
            i++;
        }
    }
    
    void deleteList(node **head)
    {
        node *temp = *head;
        node *delNode;
    
        while(temp!= NULL)
        {
            delNode = temp;
            temp = temp -> next;
            delNode -> next = NULL;
            free(delNode);            
        }
    
        free(temp);
    }
    
    int main(int argc, char *argv[])
    {
        int seed;
        int num_of_rand_nums;
        int max_value;
        int i;
        node *head = NULL;
    
        sscanf(argv[1],"%d",&seed);
        srandom(seed);
    
        sscanf(argv[2],"%d",&num_of_rand_nums);
        sscanf(argv[3],"%d",&max_value);
    
        for(i=0;i<num_of_rand_nums;i++)
        {    
            node *newNode = malloc(sizeof(node));
            if(newNode == NULL)
            {
                printf("newNode is NULL! \n");
                exit(1);
            }
            newNode -> next = NULL;
            newNode -> data = random()%(max_value + 1);
            insertNodeSorted(&head,newNode);
        }
        
        printList(head);
        deleteList(&head);
    
        return 0;
    }
  • 相关阅读:
    二分查找算法
    js 分享QQ、QQ空间、微信、微博
    linux安装redis
    redis linux开机启动 (简单高效)
    js 自定义阻止事件冒泡函数
    js常见删除绑定的事件
    js自定义方法绑定元素事件
    js 中 attachEvent 简示例
    idea无法正常显示jsp页面
    get请求的时候特殊符号的注意事项
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/12914071.html
Copyright © 2011-2022 走看看