【数据结构】逆转来链表[Clang]

   |   2 minute read   |   Using 315 words

逆转来单链表 - C语言版

#include <stdlib.h>
#include <stdio.h>
#define NODE_COUNTS 10
#define MAX_VALUE 10

typedef struct Node {
    int value;
    struct Node *next;
} Node;

typedef struct LinkedList {
    Node head;
    int length;
} LinkedList ;

Node *init_node(int value) {
    Node *p  = (Node *)malloc(sizeof(Node));
    p->value = value;
    p->next  = NULL;
    return p;
}

LinkedList *init_linked_list() {
    LinkedList *l = (LinkedList *)malloc(sizeof(LinkedList));
    l -> head.next = NULL;
    l -> length = 0;
    return l;
}

void clear_node(Node *node) {
    if (node == NULL) return ;
    free(node);
    return ;
}


void clear_linked_list(LinkedList *l) {
    if (l == NULL) return ;
    Node *p = l->head.next;
    Node *temp;
    while (p) {
        temp = p ->next;
        clear_node(p);
        p  = temp;
    }
    free(l);
    return ;
}

int insert(LinkedList *l, int pos, int value) {
    if (l == NULL) return 0 ;
    if (pos < 0 || pos > l->length) return 0;

    Node *p = &(l->head);
    Node *new_node = init_node(value);

    while(pos--) {
        p = p->next;
    }
    new_node->next = p->next;
    p->next = new_node;
    l->length += 1;
    return 1;
}


void print_linked_list(LinkedList *l) {
    printf("LinkedList(%d) ", l->length);
    for (Node *p = l->head.next; p; p = p->next) {
        printf("%d -> ", p->value);
    }
    printf("NULL\n");
    return ;
}

void reverse(LinkedList *l) {
    Node *curr, *next;
    curr = l->head.next;
    l->head.next = NULL;
    while (curr != NULL) {
        next  = curr->next;
        curr->next = l->head.next;
        l->head.next = curr;
        curr = next;
    }
}

int main(){
    LinkedList *l = init_linked_list();

    for (int i = 0; i < NODE_COUNTS; ++i) {
            insert(l, i,rand() % MAX_VALUE );
    }

    printf("\n");

    print_linked_list(l);

    reverse(l);
    print_linked_list(l);

    clear_linked_list(l);

    return 0;
}

编译运行脚本

#!/bin/bash

set -xe

cc -Wall -Wextra main.c -o main

./main

运行结果


LinkedList(10) 3 -> 6 -> 7 -> 5 -> 3 -> 5 -> 6 -> 2 -> 9 -> 1 -> NULL
LinkedList(10) 1 -> 9 -> 2 -> 6 -> 5 -> 3 -> 5 -> 7 -> 6 -> 3 -> NULL



© 2025 by clayliu. All Rights Reserved.