C program reversed linked list

前端 未结 2 1480
迷失自我
迷失自我 2021-01-28 08:46

Im trying to write a program in c that adds big numbers with linked list. I used reverse to add the numbers, but i cant get it to reverse again. It should be used several times(

相关标签:
2条回答
  • 2021-01-28 09:34

    link list reverse sample like this

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct node {
      int digit;
      struct node *next;
    } node;
    
    node *reverse_copy(node *list){
        node *new_list = NULL;
        while(list){
            node *new_node = malloc(sizeof(node));
            new_node->digit = list->digit;
            new_node->next = new_list;
            new_list = new_node;
            list = list->next;
        }
        return new_list;
    }
    
    void reverse_not_copy(node **header){
        node *tmp, *list, *newList = NULL;
        if (header==NULL || *header == NULL) return;
        list = *header;
        while(list != NULL){
            tmp = list;
            list = list->next;
            tmp->next = newList;
            newList = tmp;
        }
        *header = newList;
    }
    
    void print(node *head){
        while(head){
            printf("%d ", head->digit);
            head = head->next;
        }
        printf("\n");
    }
    
    int main(void){
        node *np;
        node n[3] = { {1,NULL}, {2, NULL}, {3, NULL}};
        n[0].next = &n[1];
        n[1].next = &n[2];
    
        print(&n[0]);//1 2 3
        np=reverse_copy(&n[0]);
        print(np);//3 2 1
        reverse_not_copy(&np);
        print(np);//1 2 3
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-28 09:47

    As the question is not very specific with the issue you're are facing, below are some points to be taken care,

    In function reverse(),

    return reversed, reversedTail; will always return reversedTail.

    You are trying to call this function from main() as

    root, head = reverseLinkedList(sum, headSum); which again head will get the return values. This is incorrect. Usually you should be using a assignment to one member at a time.

    0 讨论(0)
提交回复
热议问题