题解 | #链表中的节点每k个一组翻转# C/C++ 注释详细

C

struct ListNode* reverseKGroup(struct ListNode* head, int k ) {
    // write code here
    if(head==NULL||head->next==NULL)
        return head;
    struct ListNode* H=malloc(sizeof(struct ListNode));
    H->next=head;//由于可能对链表头结点进行修改,提前创建一个头结点连接链表
    struct ListNode* cur=head;
    struct ListNode* Newhead=H;//用于指向每组反转区间的头结点
    int flag=0;
    int i;
    while(cur!=NULL&&cur->next!=NULL)
    {
        struct ListNode *p,*q,*temp=cur;
        q=cur;//保存每组反转链表的第一个节点,即反转后与原链表相连的节点
        //判断是否越界,越界直接返回
        for(i=0;i<k;i++)
        {
            if(temp==NULL)
            {
                flag=1;
                break;
            }
            temp=temp->next;
        }
        if(flag==1)
            break;
        //头插法反转链表
        for(i=0;i<k&&cur->next!=NULL;i++)
        {   
            p=cur;
            cur=cur->next;
            p->next=Newhead->next;
            Newhead->next=p;
        }
        //正好反转无溢出节点时特殊处理
        if(i<k)
        {
            q->next=NULL;
            cur->next=Newhead->next;
            Newhead->next=cur;
            break;
        }
        q->next=cur;//反转后的链表与原链表相连
        Newhead=q;//头结点迭代
    }
    return H->next;
}

C++

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

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* reverseKGroup(ListNode* head, int k) {
        // write code here
        if(head==nullptr||head->next==nullptr)
            return head;
        if(k==1)
            return head;
        ListNode *H=new ListNode(0);
        H->next=head;
        ListNode *NewHead=H;
        ListNode *cur=head;
        int i=0;
        int flag=0;
        while(cur!=nullptr&&cur->next!=nullptr)
        {
            ListNode *q=cur;//q为每组反转链表区间第一个节点 即反转后最后一个节点
            ListNode *temp=cur;
            //查看是否越界 越界直接退出
            for(i=0;i<k;i++)
            {
                if(temp==NULL)
                {
                    flag=1;
                    break;
                }
                temp=temp->next;
            }
            cout<<flag<<endl;
            if(flag==1)
            {
                break;
            }
            //头插法反转链表
            for(i=0;i<k;i++)
            {
                temp=cur;
                cur=cur->next;
                temp->next=NewHead->next;
                NewHead->next=temp;        
            }
            q->next=cur;//与原链表连接
            NewHead=q;
//             cout<<q->val<<endl;
        }
        return H->next;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

香草绵绵冰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值