Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Đảo ngược giá trị từng nút trong danh sách liên kết đơn C

Cho danh sách liên kết đơn. Đảo ngược giá trị của từng nút (ví dụ: 34 → 43, 12 → 21).

Ví dụ

Đầu vào - 34 → 12 → 89 → 56 → 72

Đầu ra - 43 → 21 → 98 → 65 → 27

Phương pháp

  • Duyệt danh sách liên kết
  • Với mỗi nút, gọi hàm đảo số: while(n>0) {rev = rev*10 + n%10; n/=10;}
  • Cập nhật data của nút

Chương trình mẫu

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

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

struct Node* newNode(int key) {
    struct Node* t = malloc(sizeof(struct Node));
    t->data = key;
    t->next = NULL;
    return t;
}

int reverseNum(int n) {
    int rev = 0;
    while (n != 0) {
        rev = rev * 10 + n % 10;
        n /= 10;
    }
    return rev;
}

void reverseListValues(struct Node* head) {
    while (head) {
        head->data = reverseNum(head->data);
        head = head->next;
    }
}

void printList(struct Node* head) {
    while (head) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}

int main() {
    struct Node* head = newNode(34);
    head->next = newNode(12);
    head->next->next = newNode(89);
    head->next->next->next = newNode(56);
    head->next->next->next->next = newNode(72);
    
    printf("Danh sách gốc: ");
    printList(head);
    
    reverseListValues(head);
    
    printf("Danh sách sau đảo: ");
    printList(head);
    return 0;
}

Kết quả

Danh sách gốc: 34 12 89 56 72
Danh sách sau đảo: 43 21 98 65 27