链表反转

2018-09-12  本文已影响0人  陈_振
struct Node* reverseList(struct Node *head) {
    struct Node *p = head;
    
    // 反转后的链表头部
    struct Node *newListHead = NULL;
    
    // 遍历链表
    while (p != NULL) {
        // 记录下一个结点
        struct Node *temp = p->next;
        
        // 使用头插法
        // 当前结点的next指向新链表的头部
        p->next = newListHead;
        
        // 更新链表头部为当前结点
        newListHead = p;
        
        // 移动P
        p = temp;
    }
    
    return newListHead;
}

struct Node* constructList(void) {
    // 头结点
    struct Node *head = NULL;
    // 尾结点
    struct Node *tail = NULL;
    
    for (int i = 0; i < 5; i++) {
        struct Node *node = (struct Node *)malloc(sizeof(struct Node));
        node->data = I;
        
        if (head == NULL) {
            head = node;
        } else {
            tail->next = node;
        }
        
        tail = node;
    }
    
    tail->next = NULL;
    
    return head;
}

void printList(struct Node *head) {
    struct Node *temp = head;
    while (temp != NULL) {
        printf("node is %d\n", temp->data);
        temp = temp->next;
    }
}
屏幕快照 2018-09-12 下午9.52.29.png
上一篇 下一篇

猜你喜欢

热点阅读