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

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

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

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

        ListNode *test = head;
        int len = 0;
        while ( test != nullptr )
        {
            len ++;
            test = test->next;
        }

        if ( k == 1 || k > len)
        {
            return head;
        }

        int num = ( len / k );
        int j = 0;
        ListNode *res = new ListNode(0);
        ListNode *p = res;
        ListNode *temp = nullptr;
        ListNode *t = temp;
        res->next = head;
        int cur_index = 0;
        bool first = true;
        while ( head != nullptr )
        {
            cur_index =  cur_index+1;
            if ( cur_index % (k+1) == 0 ){
                temp = nullptr;
                p = t;
                t = head;
                first = true;
                j ++;
            }
            else{
                p->next = head;
                head = head->next;
                p->next->next = temp;
                temp = p->next;
                if ( first )
                {
                    t = temp;
                    first = false;
                }
            }
            if ( j == num )
            {
                p->next = head;
                break;
            }
            
        }
        return res->next;

    }
};

全部评论

相关推荐

头像
02-15 16:23
中南大学 Java
野猪不是猪🐗:签了美团真是不一样! 亲戚们都知道我签了美团,过年都围着我问送一单多少钱,还让弟弟妹妹们引以为戒,笑我爸我妈养了个🐢孩子,说从小就知道我这个人以后肯定没出息,我被骂的都快上天了
点赞 评论 收藏
分享
沟头学院:无关比赛不要写,这样会显着你主次不分,比赛不要撒谎,有哪些就写那些,创新创业建议删除。技能特长可以适当夸大。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务