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

struct ListNode { int data; struct ListNode *next; };

struct ListNode *reverse(struct ListNode *head) { struct ListNode *prev = NULL; struct ListNode *curr = head;

while (curr != NULL) {
    struct ListNode *next = curr->next;
    curr->next = prev;
    prev = curr;
    curr = next;
}

return prev;

}

struct ListNode *createlist() { int num; struct ListNode *head = NULL; struct ListNode *tail = NULL;

while (scanf("%d", &num) && num != -1) {
    struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
    node->data = num;
    node->next = NULL;
    
    if (head == NULL) {
        head = node;
        tail = node;
    } else {
        tail->next = node;
        tail = node;
    }
}

return head;

}

void printlist(struct ListNode *head) { struct ListNode *p = head;

while (p) {
    printf("%d ", p->data);
    p = p->next;
}

printf("\n");

}

int main() { struct ListNode *head;

head = createlist();
head = reverse(head);
printlist(head);

return 0;

}

C语言单链表逆置算法详解及代码实现

原文地址: https://www.cveoy.top/t/topic/golR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录