题解 | #链表中的节点每k个一组翻转#

链表中的节点每k个一组翻转

https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */
/* 检查是否可反转 */
int ChechList(struct ListNode *head, int k)
{
    int count = 1;
    struct ListNode *temp = head;

    while (temp) {
        if (count == k) {
            return 1;
        }
        temp = temp->next;
        count++;
    }

    return 0;
}
struct ListNode *Reverse(struct ListNode *head, int k)
{
    struct ListNode *preTrt = head;
    struct ListNode *trt = head;
    struct ListNode *pre = head;
    struct ListNode *cur = head;
    struct ListNode *next = head;
    struct ListNode *pHead = head; /* 反转后新的头节点 */


    while (ChechList(cur, k) == 1) {
        preTrt = trt; /* 记录反转区间的前一个节点,反转后用于连接反转区间 */
        pre = cur;
        cur = cur->next;
        trt = pre; /* 记录反转区间的开始节点,反转后为反转区间的最后一个节点,用于连接后面节点 */
        for (int i = 1; i < k; i++) {
            next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        trt->next = cur; /* 连接后反转区间的后面节点 */
        if (preTrt == trt) {
            pHead = pre; /* 新的头节点 */
        } else {
            preTrt->next = pre; /* 反转前一个节点连接反转区间反转后的区间 */
        }
    }

    return pHead;
}
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head ListNode类 
 * @param k int整型 
 * @return ListNode类
 */
struct ListNode* reverseKGroup(struct ListNode* head, int k ) {
    // write code here
    return Reverse(head, k);
}

全部评论

相关推荐

02-12 00:59
已编辑
哈尔滨工业大学 产品经理
华为 软件开发岗 20.6*16薪 本科
点赞 评论 收藏
分享
MScoding:你这个实习有一个是当辅导老师,这个和找技术岗没有关系吧?
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务