составить список из m узлов, где m берется на входе - PullRequest
0 голосов
/ 13 февраля 2020

Привет, это код, который я написал для создания столько узлов, сколько ему нужно (переменная m), но я заметил, что с помощью этого метода я создаю еще один узел. Как лучше всего создать столько узлов, сколько нам скажет пользователь?

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

typedef struct Node{
    int val;
    int rip;
    struct Node *next;
} node;

node *modify(node *head);

void print(node *head2);

int main(){

    int m, i;

    printf("How many nodes: \n");
    scanf("%d", &m);

    node *head = NULL;
    head = (node *)malloc(sizeof(node));
    node *temp = head;
    node *head2 = NULL;

    printf("Write the value in HEAD position : \n");
    scanf("%d", &temp->val);
    temp->rip=0;
    temp->next = NULL;

    for(i=0; i < m-1; i++)
    {
        temp->next = (node *)malloc(sizeof(node));
        printf("Write the value in position %d: \n", i);
        temp = temp->next;
        scanf("%d", &temp->val);
        temp->rip=0;
        temp->next = NULL;  
    }

    head2 = modify(head);

    print(head2);

    return 0;
}

node *modify(node *head){

    int counter, pass, m;

    node *curr = head;
    node *track = head;
    node *precNode;

    while (track != NULL){
        counter = 0;
        pass = 0;
        m = track->val;
        while( curr != NULL){
            if(m == (curr)->val){
                pass++;
                counter++;
                if(pass > 1){
                    node *removed = curr;

                    precNode->next = (curr)->next;

                    curr = (curr)->next;
                    free(removed);

                }
                if(pass == 1)
                {
                    precNode = curr;
                    curr = curr->next;
                }
            }
            else{
                precNode = curr;
                curr = (curr)->next;
            }    
        }
        track->rip = counter;
        track = track->next;
        curr = track;
    }

    return head;
}

void print(node *head2){

    while(head2 != NULL){
        printf("[%d, %d]  ->   ", head2->val, head2->rip);
        head2 = head2->next;
    }
    printf("\n");
} 
<span class="math-container">```</span>
...