C - 链接列表 - 以相反的方式链接

时间:2017-06-15 07:18:46

标签: c linked-list reverse

#include <stdio.h>

#include<stdlib.h>

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

void print_list(Node* head);
void CreateList(Node** head , int data);
void reverse(Node** head_ref);



int main() {
    int i, c, a;
    Node* list = NULL;

    printf("How many numbers do you want? ");
    scanf("%d",&c);
    for (i = 1; i <= c; i++) {
        printf("Enter number %d: ", i);
        scanf("%d", &a);
        CreateList(&list, a);
    }

    printf("Given linked list\n");
    print_list(list);

    reverse(&list);

    printf("\nReversed Linked list \n");
    print_list(list);

    return 0;
}

void print_list(Node* head) {
    while (head != NULL) {
        printf("%d -> ", head->data);
        head = head->next;
    }

    if (head == NULL)
        printf("NULL");

    return;
}

void CreateList(Node** head , int data) {
    Node *temp = (Node*) malloc(sizeof(Node));;

    temp->data = data;
    temp->next = *head;
    *head = temp;
}

void reverse(Node** head_ref) {
    Node* prev   = NULL;
    Node* current = *head_ref;
    Node* next;

    while (current != NULL) {
        next  = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    *head_ref = prev;
}

输入:1 2 3 4 5 6

  • 给出链接列表:6-> 5-> 4-> 3-> 2-> 1-> NULL

  • 反向链接列表:1-> 2-> 3-> 4-> 5-> 6-> NULL

我的想法是:

  • 1-> 2-> 3-> 4-> 5-> 6-> NULL-成为给定列表

  • 6-> 5-> 4-> 3-> 2-> 1-> NULL-成为反向列表

我实际上是如此努力,却找不到以正常方式创建列表的方法,任何可能的解决方案?

1 个答案:

答案 0 :(得分:1)

Your create_list() function inserts the new node at the start of the chain, pushing down the existing elsements. Instead, you could append at the end of the chain, like:


void add_at_end(Node** head ,int data)
{
    Node *temp;

      // Find the end of the chain
    while (*head) { head = & (*head)->next ; }

    temp = malloc(sizeof *temp);
    temp->next = NULL;
    temp->data = data;
      // append
    *head = temp;
}