싱글 체인 시계의 반전

싱글 체인 시계의 반전
//     
struct SingleLinkedList {
    int value;
    struct SingleLinkedList *next;
};
//         
void printAllNodes(struct SingleLinkedList *head) {
    printf("%d \t", head->value);
    if (head->next == NULL) {
        return;
    }
    printAllNodes(head->next);
}
//       
struct SingleLinkedList * reverseLinkedList(struct SingleLinkedList *head) {
    if (head == NULL) {
        return head;
    }
    if (head->next == NULL) {
        return head->next;
    }
    struct SingleLinkedList *preNode = NULL;
    struct SingleLinkedList *nextNode = NULL;
    while (head != NULL) {
        // 1.            
        //       
        nextNode = head->next;
        //             ,    
        head->next = preNode;
        
        // 2.         
        preNode = head;
        head = nextNode;
    }
    return preNode;
}

테스트
    struct SingleLinkedList *linkedRoot = (struct SingleLinkedList *)malloc(sizeof(struct SingleLinkedList));
    linkedRoot->value = 100;
    linkedRoot->next = (struct SingleLinkedList *)malloc(sizeof(struct SingleLinkedList));
    linkedRoot->next->value = 99;
    linkedRoot->next->next = (struct SingleLinkedList *)malloc(sizeof(struct SingleLinkedList));
    linkedRoot->next->next->value = 98;
    linkedRoot->next->next->next = (struct SingleLinkedList *)malloc(sizeof(struct SingleLinkedList));
    linkedRoot->next->next->next->value = 97;

    printf("   :\t");
    printAllNodes(linkedRoot);

    printf("\r
:\t"
); struct SingleLinkedList * reversedLinked = reverseLinkedList(linkedRoot); printAllNodes(reversedLinked);

좋은 웹페이지 즐겨찾기