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

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

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

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

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    void reverse(ListNode* list){
        ListNode* pre = nullptr, *cur = list, *next;
        while(cur){
            next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
    }
    
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(!head || k == 1) return head;
        // write code here
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        
        ListNode* pre = dummy, *cur = head, *next = cur, *next_head;
        while(next->next){
            for(int i = 1; i < k; i++){
                if(next->next){
                    next = next->next;
                }else{
                    return dummy->next;
                }
            }
            next_head = next->next;
            pre->next = nullptr;
            next->next = nullptr;
            reverse(cur);
            //connect
            pre->next = next;
            cur->next = next_head;
            //change
            pre = cur;
            cur = next_head;
            next = cur;
            if(cur == nullptr) break;
        }
        return dummy->next;
    }
};
全部评论
好像在哪也碰到类似的问题,感觉相对来说,一目了然
点赞 回复 分享
发布于 2022-10-23 20:45 陕西

相关推荐

11-15 19:28
已编辑
蚌埠坦克学院 硬件开发
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务