题解 | #重排链表#

重排链表

https://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

/**
 * 
 * @param head ListNode类 
 * @return  void
 */

struct ListNode *FindLastNode(struct ListNode *head)
{
    if (head->next == NULL) {
        return head;
    }

    struct ListNode *temp = head->next;
    if (temp->next == NULL) {
        head->next = NULL;
        return temp;
    }

    return FindLastNode(head->next);
}

void reorderList(struct ListNode* head ) {
    // write code here
    struct ListNode *temp = head;
    struct ListNode *lastNode = NULL;

    if ((head == NULL) || (head->next == NULL)) {
        return;
    }

    while (temp != NULL) {
        lastNode = FindLastNode(temp);
        lastNode->next = temp->next;
        if (temp != lastNode) {
            temp->next = lastNode;
        }
        temp = lastNode->next;
    }
}

全部评论

相关推荐

11-08 17:36
诺瓦科技_HR
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务