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

标签 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 - 反转列表

我实际上很努力地尝试过,但找不到以正常方式创建列表的方法,有什么可能的解决方案吗?

最佳答案

您的 create_list() 函数会在链的开头插入新节点,向下推现有的其他节点。相反,您可以附加在链的末尾,例如:

<小时/>
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;
}

关于C - 链表 - 以相反的方式链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44561095/

相关文章:

c - 如何检查 free(node) 是否有效

css - 反向 CSS3 过渡

python - 在python中构造一个从大到小的整数列表

c - xTicksToWait = portMAX_DELAY时,xQueueReceive会失败吗?

c - 与管道的双向通信

c - 为链表数组分配内存

c - 在c中将文本文件逐行保存到链表中

string - 在 Julia 中反转字符串

c - scanf 的异常行为

c++ - 计算密集型C/C++程序的典型性能瓶颈是什么